Daniel Peñalba
Daniel Peñalba

Reputation: 31847

When the ThreadPool constructs new threads instead reusing them?

I read the following paragraph in the following answer from Reed Copsey:

Will values in my ThreadStatic variables still be there when cycled via ThreadPool?

The thread pool (by design) keeps the threads alive between calls. This means that the ThreadStatic variables will persist between calls to QueueUserWorkItem.

This behavior is also something you should not count on. The ThreadPool will (eventually, at its discretion) release threads back and let them end, and construct new threads as needed.

Under what conditions the threadpool eventually constructs new threads instead reusing them?

Upvotes: 1

Views: 476

Answers (2)

dcastro
dcastro

Reputation: 68640

As Adriano said, this is an implementation detail you should not worry about. But, for curiosity's sake, this is the best explanation of how the ThreadPool works that I could find (from Throttling Concurrency in the CLR 4.0 ThreadPool):

To overcome some of the limitations of previous implementations, new ideas were introduced with CLR 4.0. The first methodology considered, from the control theory area, was the Hill Climbing (HC) algorithm. This technique is an auto-tuning approach based on an input-output feedback loop. The system output is monitored and measured at small time intervals to see what effects the controlled input had, and that information is fed back into the algorithm to further tune the input. Looking at the input and output as variables, the system is modeled as a function in terms of these variables.

Simply put, once in a while, the Hill Climbing algorithm,

  1. Measures the output using the current number of threads (n).
  2. Adds +1 thread to the pool
  3. Measures the output using the current number of threads (n+1).
  4. If O(n+1) > O(n)
    1. go back to step 1;
    2. else, go back to step 1, but this time release a thread at step 3, instead of creating a new one.

Upvotes: 2

Remus Rusanu
Remus Rusanu

Reputation: 294217

AFAIK under 'undocumented' conditions.

First and foremost consider that there are at least 4 commonly used CLR hosting providers (ASP.Net, IE, shell exes and SQLCLR) and each has its own policies. For instance SQLCLR hosting uses the SQL Server's own Thread and Task architecture and will react to OS signals of pressure by shrinking pools (all sort of pools, including threads).

So why not just assume that the thread was always reclaimed and you'll be correct (ie. don't keep state on the pool owned thread).

Upvotes: 1

Related Questions