Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join threads from thread pool

I have 30+ tasks that can be executed in parallel.
I use ThreadPool for each task.
But parent-function should not return until all tasks has completed.

I need a thread sync handle that would release WaitOne when its count reaches 0. Something like:

foo.StartWith(myTasks.Count);
foreach (var task in myTasks) {
    ThreadPool.QueueUserWorkItem(state => { task(state); foo.Release(); });
}
foo.WaitOne();

Semaphore feels right, just can't figure out how to apply it here.

like image 737
THX-1138 Avatar asked Jul 23 '26 15:07

THX-1138


1 Answers

int running = myTasks.Count;
AutoResetEvent done = new AutoResetEvent(false);
foreach (var task in myTasks) {
    ThreadPool.QueueUserWorkItem(state => { 
    task(state); 
    if (0 == Interlocked.Decrement(ref running))
      done.Set ();
    });
}
done.WaitOne();

With C# 4.0 you can use the new CountdownEvent primitive.

like image 126
Remus Rusanu Avatar answered Jul 26 '26 05:07

Remus Rusanu