BjartN
BjartN

Reputation: 5487

Running one parallel task per processor using the Task Parallel Library in C#

When using the task parallel library, is it possible to make sure that I am only running one task per processor at the time? And if not, what is the best way to do this in C#?

Note: I am not doing this to increase performance, but to make the timing of each task more reliable. For more info see this question: Timing of parallel actions using the Task Parallel Library in C#

Upvotes: 1

Views: 1537

Answers (2)

svick
svick

Reputation: 244777

First, if you want to have absolutely reliable timing, then using Windows and .Net are not the right choices. Windows because it's not a real-time OS and it can choose different timing for your code based on other things happening in the system. .Net is not a good choice because it has non-deterministic timing thanks to the garbage collector.

But if you just want to make the timing somewhat more reliable, there are some things you can do.

If you want to run each thread on its own processor, you could manually create the Threads and then set ProcessThread.ProcessorAffinity for each thread, but getting the ProcessThread for a Thread is not that simple.

If you just want to make sure all the tasks start immediately (no matter what other tasks are currently running on the ThreadPool), you should create your own Threads too.

But if all you want is to make sure that there is at most one task per processor, just set MaxDegreeOfParallelism to Environment.ProcessorCount.

Upvotes: 5

Phil
Phil

Reputation: 42991

You can use ParallelOptions to specify the max parallelism. However this is an upper bound, it won't force one thread per core, other constraints may mean less cores are used.

e.g.

var list = new List<int>();
var options = new ParallelOptions();
options.MaxDegreeOfParallelism = 4;

Parallel.ForEach(list, options);

Upvotes: 1

Related Questions