I have an application with one main thread and N worker threads. At some point I need that the main thread waits until all the N threads have completed one section of their work.
I normally would use Monitor.Wait() and Monitor.Pulse() but this will prevent the N threads from working at the same time.
Any idea on how to do that?
Thanks in advance.
.NET 4.0 will include the System.Threading.Barrier
class that will make synchronization between multiple threads easier. A blog post with some good example code can be found here.
Similar functionality can be achieved using multiple WaitHandles in .NET 3.0+, as demonstrated in this example on MSDN.
A brief summary of the MSDN example:
const int numberOfWorkers = 5;
static void Main()
{
var handles = new ManualResetEvent[numberOfWorkers];
for (int i = 0; i < numberOfWorkers; i++)
{
handles[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(o => worker.Work(), null);
}
// Wait for all workers to finish before continuing
WaitHandle.WaitAll(handles);
/* continue execution... */
}
Do something similar to garbage collection. You'll write a ThreadManager that has a count of how many threads are running. When the main thread starts a new worker, the ThreadManager will increment its count of workers. When a worker finishes, it will inform the ThreadManager who will decrement its count of threads. When it has zero worker threads, the ThreadManager will wake the main thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With