sudeepdino008
sudeepdino008

Reputation: 3364

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?

Upvotes: 5

Views: 10821

Answers (2)

Vincent
Vincent

Reputation: 13415

Here is an example :

from threading import Thread, Lock
from time import sleep
from random import random

def target(i, lock):
    with lock:
        print("Starting thread {}".format(i))
    # Do something
    sleep(random()*5)
    with lock:
        print("Stopping thread {}".format(i))

# Create the threads
lock = Lock()
threads = [Thread(target=target, args=(i, lock)) for i in range(5)]

# Start the threads
for x in threads:
    x.start()

# Stop the threads
for x in threads:
    x.join()

print("Done!")

And this is a possible output:

>>>
Starting thread 0
Starting thread 1
Starting thread 2
Starting thread 3
Starting thread 4
Stopping thread 1
Stopping thread 4
Stopping thread 0
Stopping thread 2
Stopping thread 3
Done!

You can see that it works as you need it to.

Upvotes: 2

Patrick Collins
Patrick Collins

Reputation: 10584

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).

Upvotes: 7

Related Questions