Parallel and work division in c#?

2019-04-08 15:10发布

(let's assume I have 10 cores)

When I write:

Parallel.For(0, 100, (i,state) =>  
         { 
            Console.WriteLine(i); 
         });

Questions:

  1. What is the formula of assigning amount of numbers to each core? (is it 100/10?)

  2. At execution point, does each core already know which numbers is is gonna handle? Or does it consume each time a new number/s from the [0..100] repository (let's ignore chunk or range for now)?

  3. The i parameter - does it refer to the 0..100 index or is it a relative index in each thread and its "gonna handle" numbers?

1条回答
来,给爷笑一个
2楼-- · 2019-04-08 15:52
  1. It is not documented. Probably the worker tasks check out chunks of work from a shared work pool. Probably they take less than 10 items at once because taking 10 items would lead to less than 10 threads being at work near the end of the Parallel.For operation. A single slow thread could create a sequential bottleneck because it might be the only thread still running. It is better to partition the work in smaller chunks so that this type of bottleneck becomes smaller.

  2. I don't know. I'm pretty sure one would have to pry this information out using Reflector.

  3. It refers to the global index so you can use it to access a shared list or something. Every i ever seen by your work delegate will be unique.

查看更多
登录 后发表回答