Skip to content

ThreadLocal<T> using more instances than cores available #114681

Answered by stephentoub
BarionLP asked this question in Q&A
Discussion options

You must be logged in to vote

Parallel.ForEach isn't bound to only use a number of threads equal to the number of cores. By default, it'll use as many thread pool threads as are available. If you want to limit the number of concurrent operations used, pass in a ParallelOptions that sets MaxDegreeOfParallelism. Even then, though, you may find yourself with more thread-local values than what you set, if the tasks Parallel.ForEach uses internally end up hopping around between threads (to help with fairness, every now and then the tasks involved will decide to queue a replica of themselves and then go away, to give the thread pool the opportunity to schedule them as it sees fit).

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@BarionLP
Comment options

Answer selected by danmoseley
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants