Understand join() in Python Threading with Examples: A Beginner Guide – Python Tutorial

By | December 16, 2019

To create a multithreading application, one of problem is to how to make these threads can run one by one. To address this issue, we can use thread.join() function. In this tutorial, we will use some examples to illustrate this function for python beginners.

Create 10 threads in python

We create 10 threads first in our python script. Each thread will print its thread name. The example code is below:

import threading
import time
 
def test(name):
    time.sleep(2)
    print("run "+ name)
 
ts = []
 
#create 10 threads 
for i in range(10):
    thread_name = 'thread ' + str(i)
    th = threading.Thread(target=test, args=[thread_name])
    ts.append(th)

Then we will start these threads one by one.

#run thread one by one 
for i in ts:
    i.start()

Run this python script, we will find the output is:

understand python threading join() function examples

From the result we can find these threads are not finished as the order we start them.

How to make these threads are finished as the order we start?

To gain this aim, we should use thread.join() function, which means the next thread can be run after the current thread is finished.

For example, if we start threads like below:

for i in ts:
    i.start()
    i.join()

Run this python script, you will find the result is:

understand python threading join() function examples and tutorials

We can find these threads are finished as the order we start them.

Moreover, look at example below:

import threading
import time
 
def test(name):
    for i in range(10):
        time.sleep(1)
        print("run "+ name + ": " + str(i))
    print("thread is finished")

thread_name = 'test thread' 
th = threading.Thread(target=test, args=[thread_name])
th.start() 
time.sleep(5)
print("main application is finished")

In this example, we will run a sub thread in main thread, however, we will find the main thread is finished while the sub thread is still running.

Here is result:

python main application is finished and thread is running

To void the problem that the main is over while the sub thread is still running, we can use thread.join().

Look at code below:

thread_name = 'test thread' 
th = threading.Thread(target=test, args=[thread_name])
th.start() 
th.join()
time.sleep(5)
print("main application is finished")

Run this python script, we will find the result is:

python main application is finished and thread is finished

We can find the main thread will be finished after the sub thread is end.

Leave a Reply