Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadPool max threads

I've got some trouble with .NET's ThreadPool (.NET 4).

I've read that by default .NET has a limit of 25 threads per processor, but according to forum posts on SO and on other places, I can increase the limit with the below code.

void SetThreads(int threads) {     ThreadPool.SetMaxThreads(threads, threads);     ThreadPool.SetMinThreads(threads, threads); } 

However, when I set the above to some arbitrarily high number, for example, 2000, and queue ~1000 items, I still only have ~33 threads running (.NET CLR takes ~5 threads), and ThreadPool.GetAvailableThreads() returns 1971 threads remaining.

Why doesn't the code above work?

like image 924
foxy Avatar asked May 14 '11 09:05

foxy


People also ask

How many maximum threads can be created using a ThreadPool?

ThreadPool will create maximum of 10 threads to process 10 requests at a time. After process completion of any single Thread, ThreadPool will internally allocate the 11th request to this Thread and will keep on doing the same to all the remaining requests.

How many threads can you create C#?

32767 in Framework 4.0 (64-bit environment)

What is an ideal ThreadPool size?

4 cores = 400 / second (or 800 maybe with HT). The blocking coefficent is 90ms/10ms = 9. So the ideal thread pool size is 4 cores * 2 * ( 1 + 9 ) = 80.


2 Answers

From the MSDN :

When demand is low, the actual number of thread pool threads can fall below the minimum values.

Read this too: Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4

like image 26
Emond Avatar answered Oct 05 '22 23:10

Emond


Firstly, your "knowledge" of the defaults is incorrect. The limit of 25 threads per processor was back from .NET 1.1. It was increased in .NET 2, and now:

Beginning with the .NET Framework version 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.

However, there's something else at play: the thread pool doesn't immediately create new threads in all situations. In order to cope with bursts of small tasks, it limits how quickly it creates new threads. IIRC, it will create one thread every 0.5 seconds if there are outstanding tasks, up to the maximum number of threads. I can't immediately see that figure documented though, so it may well change. I strongly suspect that's what you're seeing though. Try queuing a lot of items and then monitor the number of threads over time.

like image 127
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet