Example of Multithreading in Python

Before starting to study multithreading, we will study threading. Threading is the happening of two or more things simultaneously.

We can schedule a thread in Python to execute at a preferred time. Threads are the most important and basic part when it comes to multithreading.

What is multithreading? Multithreading is executing multiple threads simultaneously. Multithreading has various advantages and multithreading in Python is very user-friendly too.

Example of multithreading:

Example 1: Multithreading in Python

from _thread import start_new_thread
from time import sleep

t_ID = 1 
waiting_1 = 2 

def fact(n):
    global t_ID
    t= 0
    if n < 1:   
        print("{}: {}".format('\nThread', t_ID ))
        t_ID+= 1
        t = 1
        return_1 = n * fact( n - 1 )  
        print("{} != {}".format(str(n), str(return_1)))
        t = return_1
    return t

start_new_thread(fact, (3, ))
start_new_thread(fact, (5, ))

print("Waiting for threads...")


Waiting for threads...

Thread: 1
1 != 1
2 != 2
3 != 6
4 != 24
5 != 120

Thread: 2
1 != 1
2 != 2
3 != 6

Here in the above example, we are using two methods to find the factorial of numbers. One of them is the conventional way of finding the factorial and that is using Recursion and then calling the function(recursion) using thread.

From the thread library, we imported the stat_new_thread, and from the time library, we imported the sleep function(as shown in the above program). We used the recursion function for the calculation of the factorial of any number “n”.

After calculating the factorial we used the thread method to call the function factorial. We can see this in the above example as we have used “start_new_thread(fact, (3, ))” to call the fact function.

Advantages of multithreading are:

  • It helps to maintain and increase the efficiency and performance of any computational work.
  • Saves execution time and multithreading also has global and local variables.

Another example of multithreading:

Example 2:

import threading
import time
print("Values from 0 to 6: ")
def thread_1():
    for i in range(0, 7):


Values from 0 to 6: 

In the above example, we are using multithreading to print the values from 0 to 6. We imported the thread and time library using import and defined a “thread_1” function using the def function. We then used a for loop to read all the values from 0 to 6 and induced a sleep time of 1 second. And culminated the program by calling the “thread_1” function using threading.Thread().

Refer to How to Start a Thread in Python for more about starting a thread in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *