views:

632

answers:

4

Hi

I have a threading issue,

I'm setting the ThreadPool.SetMaxThreads(maxThreads, System.Environment.ProcessorCount) to 10 for example.

But when I check how many are avaliable ThreadPool.GetAvailableThreads() it tells me theres (maxThreads - 1) so 9 in the example, but then goes onto use 10 threads.

Any ideas why this is?

Thanks for the help.

+1  A: 

I don't know the answer to the question, but what is the "issue" that you say this is causing? You shouldn't really be messing with these numbers... if you want a throttled pool, you should write your own (or wait until .NET 4.0 arrives, since the CCR/TPL contains such...).

Marc Gravell
What the potser has failed to mention is that they are only seeing this behaviour when run in test runner host process: http://stackoverflow.com/questions/320280/c-threadpoolsetmaxthreads-returning-false#320287
Mitch Wheat
The problem is why is the count different? Im carrying out Unit Testing on a subsystem and needed to verify that a system frees all of its threads once it has finished doing work, but each time I call GetAvaliableThreads it gives me one less than the actual real value.
No, that is untrue, as I have mentioned before this is a different problem. Even on a colleagues machine who is not carrying out unit testing this problem exists.
I think you are seeing a problem where there isn't one. As Marc pointed out "You shouldn't really be messing with these numbers"
Mitch Wheat
Why should I not mess with them, C# provides the functionality to limit the number of threads avaliable and that is what I am doing.
@MeeMMeeM - my main power circuit provides the functionality to mess with live AC; that doesn't make it a good idea...
Marc Gravell
+1  A: 

In an ideal world, we would have 1 thread/physical core. That way, we would no longer have context switches, which are rather costly operations. But until we have processors with hundreds of cores, that won't be practical.

Anyway, as Marc suggested, you shouldn't mess with the ThreadPool parameters unless you REALLY know what you are doing. The logic behind the .Net implementation of the ThreadPool is rather good, and it can successfully handle most scenarios.

Silviu Niculita
+1  A: 

Are you queuing threads with something similar?

ThreadPool.QueueUserWorkItem(callback, obj)

and then doing something like:

WaitHandle.WaitAll(WaitHandle)

My guess is that there's a problem with how you're actually counting the threads that are running, but without a more specific explanation of what you're doing, it's only a guess.

Ian P
A: 

One of the threadpool threads is monitoring the wait operations of the other threads in the thread pool. That should explain the maxthreads - 1 result.

I am not sure why it would appear to use all 10 threads then. It might be that it is using 9 for your work, 1 for monitoring and queuing the other.

Mike Two