So here's a minimal version of code that works, but is inefficient:
Parallel.ForEach(list, x =>
{
doThing1(x);
});
Thing1Done = true;
Parallel.ForEach(list, x =>
{
doThing2(x);
});
Thing2Done = true;
Parallel.ForEach(list, x =>
{
doThing3(x);
});
Thing3Done = true;
Intuitively, I'd like to run all 3 "things" within the same loop, but they must be able to synchronize temporarily to update the respective Thing*n*Done
property.
Pseudocode for this idea as follows:
Parallel.ForEach(list, x =>
{
doThing1(x);
// wait for doThing1 to be completed for all other elements in list
Thing1Done = true;
doThing2(x);
// wait for doThing2 to be completed for all other elements in list
Thing2Done = true;
doThing3(x);
// wait for doThing3 to be completed for all other elements in list
Thing3Done = true;
});
So for example, it's necessary that doThing1()
finishes its execution for every member of list
before Thing1Done
is set to true. doThing2()
can only begin after Thing1Done
has been set.
Each individual step is not overly expensive, and I'm concerned about the overhead involved with the naive approach. What is the best way to efficiently solve this task, assuming that the overhead involved in initializing the threads is my largest concern? I'd also like to avoid busy waiting (where the thread spins in a while loop doing nothing useful until some flag is set to true) if at all possible.
I am willing to write something more general if the Parallel library cannot do what I want.