Multi-threading in Python - Tutorial


Multi-threading in Python

Multithreading is a concept of executing different pieces of code concurrently. A thread is an entity that can run on the processor individually with its own unique identifier, stack, stack pointer, program counter, state, register set and pointer to the Process Control Block of the process that the thread lives on.

In this tutorial, we will learn with examples on how to do multithreading in Python programming.

threading module is used to achieve mutlithreading in Python.

Create a Thread

To create a thread, you can use threading.Thread() class. The syntax of Thread() class is:

threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
  • leave group as None.
  • target is the callable object to be invoked by the run() method of Thread.
  • name is the Thread name that you can provide and refer to later in the program.
  • args is the argument tuple for the target invocation.
  • kwargs is a dictionary of keyword arguments for the target invocation.
  • daemon is not None, will be set to be daemonic.

Start a Thread

Once you have created a thread using Thread() class, you can start it using Thead.start() method.

t1 = threading.Thread()
t1.start()

Wait until the thread is finished

You can make the Program Counter of the main process to wait until a specific thread is finished. All you have to do is call join() method on the Thread object.

t1.join()

The execution in the main program waits here at this statement until t1 completes its target execution.

Example - Python Mutlithreading with Two Threads

In the following example, we will do multi-threading with two threads. Each thread runs in parallel to the other and is executed whenever processing resources are available to it.

To fully demonstrate this behavior, we will run a function, in each thread, that prints ones and twos.

Python Program

import threading 
  
def print_one(): 
	for i in range(10):
		print(1)
  
def print_two(): 
	for i in range(10):
		print(2)
  
if __name__ == "__main__": 
	# create threads
	t1 = threading.Thread(target=print_one) 
	t2 = threading.Thread(target=print_two) 
	
	# start thread 1 
	t1.start() 
	# start thread 2 
	t2.start() 
	
	# wait until thread 1 is completely executed 
	t1.join() 
	# wait until thread 2 is completely executed 
	t2.join() 
	# both threads completely executed 
	
	print("Done!") 

Output

1
1
1
2
2
2
1
1
2
1
2
2
2
2
2
2
1
1
1
1
Done!

You could observe that after the thread1 has executed the for loop for three iterations, thread2 has got the resources and started executing. It is highly improbable to predict the amount of time a thread could get for execution.

Example - Mutlithreading with Arguments passed to Threads

In our previous example, we started threads with only their targets. Now, we will pass some arguments to them. Also, you can call the same target for different threads.

Python Program

import threading 
  
def print_x(x, n): 
	for i in range(n):
		print(x)
  
if __name__ == "__main__": 
	# create threads
	t1 = threading.Thread(target=print_x, args=(1, 5,)) 
	t2 = threading.Thread(target=print_x, args=(2, 10,)) 
	
	# start thread 1 
	t1.start() 
	# start thread 2 
	t2.start() 
	
	# wait until thread 1 is completely executed 
	t1.join() 
	# wait until thread 2 is completely executed 
	t2.join() 
	# both threads completely executed 
	
	print("Done!") 

Output

1
1
1
2
2
2
2
1
2
1
2
2
2
2
2
Done!

Summary

In this tutorial of Python Examples, we learned how to implement multi-threading in Python programming with the help of well detailed examples.