Reputation: 185
I am using a parallel.for set up:
Parallel.For(0, 4, new ParallelOptions { MaxDegreeOfParallelism = 4 }, j =>
I am expecting it to create 4 worker threads, however the concurrency visualizer only shows 3 worker threads are being used. i have tried to use max degree of parallelism and processor affinity, however under each scenario only 3 worker threads are used, not 4. Is there an obvious answer to why this is happening? cheers
Upvotes: 3
Views: 206
Reputation: 2267
Parralel.For has no idea how much irritations you will put to it, its flexible, it handles thread queues and at runtime its decided what available core is receiving a certain work-thread from threadque. A core might not be available as it is not only your code running on a windows machine. Or a core might still be bussy on a previous workload you gave it.
Here more in-depth info http://reedcopsey.com/2010/01/26/parallelism-in-net-part-5-partitioning-of-work/
Upvotes: 0
Reputation:
As stated, you only can specify the maximum, not the actual number of threads. If you have four available cores, and the workload is nontrivial, all four will run in parallel as the thread you started the For
from is also used to execute workitems.
In addition, Parallel.For
may chunk your input range. It probably won't for four items, but if you're concerned, you can schedule 4 items at once with Parallel.Invoke()
.
Upvotes: 0
Reputation: 942
This is by design, I can't remember where I read it, but it uses the thread pool underneath, and it just takes the tasks as there is processor power to do so. Though it sound strange that there is a difference between C# and F#.
In theory it should also depend on the processor cores available. If there is only one core, then there is no need to spin up more than one thread.
If you want to force it to use 4 you can write your own scheduler.
Upvotes: 0
Reputation: 17612
It is as it says MaxDegreeOfParallelism
, so it won't go above that but it won't use more than deemed necessary either.
This is what it says on MSDN:
By default, For and ForEach will utilize however many threads the underlying scheduler provides, so changing MaxDegreeOfParallelism from the default only limits how many concurrent tasks will be used.`
Upvotes: 1