Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I wait for multiple threads to stop?

I have a Main thread that spawns around 20 worker threads.
I need to stop the Main thread until all the other threads are finished.
I know about (thread).Join. But that only works for one thread.

and multiple Joins hurt performance like this.

t1.Join()
t2.Join()
...
t20.Join()

as the program waits one by one for each to stop.

How would I make it such that the main thread waits for all of a set of threads to end?

like image 646
akshaykarthik Avatar asked Sep 05 '10 14:09

akshaykarthik


2 Answers

You should really look into Task Parallelism (Task Parallel Library). It uses a thread-pool, but also manage task-stealing etc.

Quote: "The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available. In addition, the TPL handles the partitioning of the work, the scheduling of threads on the ThreadPool, cancellation support, state management, and other low-level details." on Task Parallel Library

You can use it like this:

Task[] tasks = new Task[3]
{
    Task.Factory.StartNew(() => MethodA()),
    Task.Factory.StartNew(() => MethodB()),
    Task.Factory.StartNew(() => MethodC())
};

//Block until all tasks complete.
Task.WaitAll(tasks);

Or if you use some kind of a loop to spawn your threads:

Data Parallelism (Task Parallel Library)

like image 66
Lasse Espeholt Avatar answered Oct 23 '22 19:10

Lasse Espeholt


The joins are fine if that's what you want it to do. The main thread still has to wait for all the worker threads to terminate. Check out this website which is a sample chapter from C# in a Nutshell. It just so happens to be the threading chapter: http://www.albahari.com/threading/part4.aspx.

like image 25
Chris Laplante Avatar answered Oct 23 '22 18:10

Chris Laplante