Python Code Example: join threads

In this example, a function worker is defined that takes a single argument and performs some work by sleeping for 2 seconds. The main thread creates 5 threads, each of which runs the worker function with a different argument. The threads are started using the start method and then joined using the join method, which blocks the main thread until all of the threads have completed.

import time
import threading

def worker(num):
    """Thread worker function"""
    print("Worker {}: started".format(num))
    time.sleep(2)
    print("Worker {}: finished".format(num))

threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print("Main: done")