4

This question is based on Jeffrey Richter's threading class in Microsoft Virtual Academy.

As per my understanding if I set my processor affinity to use only 1 processor as shown below

Int32 affinity = 1; Process.GetCurrentProcess().ProcessorAffinity = (IntPtr)affinity; for (int i = 0; i < 200 ; i++) { ThreadPool.QueueUserWorkItem(ActiveWorker); } 

ActiveWorker() is a CPU bound function that just do some CPU bound computation that takes around 100ms. When I count number of threads created its around 5. But as per my understanding since CPU affinity is set to use only 1 processor, thread pool should not create more than 1 thread. Any idea? In Jeffrey's presentation it was showing it created only 1 thread for entire 200 workitem, but when I ran the same sample in my PC, I can see 5 thread created. (My PC has 2 cores)

1
  • After downgrading to the .NET 3.5 ThreadPool began taking into account the value of Process.ProcessorAffinity Commented Jan 10, 2017 at 1:35

1 Answer 1

0

Default is one threadpool per processor but the number of threads in that threadpool is calculated by .Net. Here is an excerpt From MSDN https://msdn.microsoft.com/en-us/library/system.threading.threadpool(v=vs.110).aspx:

There is one thread pool per process. Beginning with the .NET Framework 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space. A process can call the GetMaxThreads method to determine the number of threads. The number of threads in the thread pool can be changed by using the SetMaxThreads method. Each thread uses the default stack size and runs at the default priority.

Sign up to request clarification or add additional context in comments.

3 Comments

Perhaps you want to put the link of where you got that from in case the OP wants to go to that link to read more.
Not sure if I got a clear understanding from the comments. If I put processor affinity to use only 1 CPU and I queued 200 work items each taking around 100 milliseconds to the Thread Pool, I was thinking thread pool shouldn't create more that one thread. But I am seeing 5 threads created eventhough I have only 4 logical CPU in my PC. (This was not my understanding). Its important that all my work items are CPU bound task and no IO waits..
@DevMonk (bit late to the party) AFAIK this is to prevent starvation, where a few tasks prevent other tasks from running. If you want tight control, the global thread pool isn't appropriate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.