ThreadLocal<T>
using more instances than cores available
#114681
-
I'm accumulating a lot of proccess data on multiple threads and then combining the accumulators of each thread using using var accumulators = new ThreadLocal<Accumulator>(Accumulator.Create, trackAllValues: true);
Parallel.ForEach(data, options, (item, state) =>
{
var result = heavyOperation(item);
accumulators.Value.Add(result);
}); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
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). |
Beta Was this translation helpful? Give feedback.
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).