Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit number of processors used in ThreadPool

Is there any way to limit the number of processors that the ThreadPool object will use? According to the docs, "You cannot set the number of worker threads or the number of I/O completion threads to a number smaller than the number of processors in the computer."

So how can I limit my program to not consume all the processors?

like image 753
tuj Avatar asked Dec 02 '22 22:12

tuj


1 Answers

After some experiments, I think I have just the thing. I've noticed that the ThreadPool considers the number of processors in the system as the number of processors available to the current process. This can work to your advantage.

I have 4 cores in my CPU. Trying to call SetMaxThreads with 2:

ThreadPool.SetMaxThreads(2, 2);

fails since I have 4 cores and so the numbers remain at their initial values (1023 and 1000 for my system).

However, like I said initially, the ThreadPool only considers the number of processors available to the process, which I can manage using Process.ProcessorAffinity. Doing this:

Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(3);  

limits the available processors to the first two cores (since 3 = 11 in binary). Calling SetMaxThreads again:

ThreadPool.SetMaxThreads(2, 2);

should work like a charm (at least it did for me). Just make sure to use the affinity setting right at program start-up!

Of course, I would not encourage this hack, since anyway your process will be stuck with a limited number of cores for the entire duration of its execution.

like image 185
Tudor Avatar answered Dec 21 '22 01:12

Tudor