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:
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:
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:
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:
We can find the main thread will be finished after the sub thread is end.