I'm going to outline how I did this a while ago:
- Create N threads
- Put the work items into a list of known size
- Have a shared variable
int lastIndex = -1;
Have all the threads do this:
while(true) { var index = Interlocked.Increment(ref lastIndex); if (index >= list.Count) return; ProcessItem(list[index]); }
Very simple.
Abstract all of this away into a helper method. It should take a delegate so that you don't need to hard-code ProcessItem
.
This helper is actually useful even for .NET 4.5 in cases where you need guaranteed exact degree of parallelism which the thread-pool does not provide.