Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop one thread until n threads have completed their work

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.

like image 705
Ignacio Soler Garcia Avatar asked Dec 03 '22 06:12

Ignacio Soler Garcia


2 Answers

.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... */
}
like image 102
Justin Rusbatch Avatar answered Dec 17 '22 16:12

Justin Rusbatch


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.

like image 34
David Souther Avatar answered Dec 17 '22 14:12

David Souther