Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make the main thread wait until all threads finish

So I have a list of threads, all started(using threading.start()), and I have to block the main thread all the threads in the list finish.

This can be achieved by:

[x.join() for x in threads]

However, for each x.join() executed, all other threads are also blocked. What I want is that all the threads execute parallel to each other. The main program should resume only when ALL the threads are executed and no thread in the list should be blocked at any time.

As far as I have understood, what I want does not happen with the join method, or am I wrong?

like image 620
sudeepdino008 Avatar asked Aug 12 '14 07:08

sudeepdino008


1 Answers

No, x.join() only blocks the main thread. The other threads continue to execute in parallel.

for thread in threads:
    thread.join()

is somewhat more idiomatic, since you're not actually building a list.

You should also be aware that multithreading doesn't work as expected in Python, and it's unlikely that you'll get any performance gain from this unless you're doing work that's IO-bound (i.e. hitting a remote service many times).

like image 120
Patrick Collins Avatar answered Sep 22 '22 06:09

Patrick Collins