Multithreading in Python
A program or process's smallest unit is called a thread, and it can run on its own or as part of a
schedule set by the Operating System. Multitasking in a computer system is achieved by dividing a
process into threads by an operating system.
There are two main modules of multithreading used to handle threads in Python.
1. The thread module
2. The threading module
Thread modules
It is started with Python 3, designated as obsolete, and can only be accessed with _thread that
supports backward compatibility.
import thread # import the thread module
import time # import time module
def cal_sqre(num): # define the cal_sqre function
print(" Calculate the square root of the given number")
for n in num:
[Link](0.3) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)
def cal_cube(num): # define the cal_cube() function
print(" Calculate the cube of the given number")
for n in num:
[Link](0.3) # at each iteration it waits for 0.3 time
print(" Cube is : ", n * n *n)
arr = [4, 5, 6, 7, 2] # given array
t1 = [Link]() # get total time to execute the functions
cal_sqre(arr) # call cal_sqre() function
cal_cube(arr) # call cal_cube() function
print(" Total time taken by threads is :", [Link]() - t1) # print the total time
Output
----------
Threading Modules
import threading
def print_hello(n):
Print("Hello, how old are you? ", n)
T1 = [Link]( target = print_hello, args = (20, ))
[Link]()
[Link]()
Print("Thank you")
Output:
Hello, how old are you? 20
Thank you
Synchronizing Threads in Python
It is a thread synchronization mechanism that makes sure that no two threads can run the
same part of the program at the same time to access shared resources. Critical sections
could be used to describe the situation. To avoid the critical section condition, in which two
threads cannot simultaneously access resources, we employ a race condition.
import time # import time module
import threading
from threading import *
def cal_sqre(num): # define a square calculating function
print(" Calculate the square root of the given number")
for n in num: # Use for loop
[Link](0.3) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)
def cal_cube(num): # define a cube calculating function
print(" Calculate the cube of the given number")
for n in num: # for loop
[Link](0.3) # at each iteration it waits for 0.3 time
print(" Cube is : ", n * n *n)
ar = [4, 5, 6, 7, 2] # given array
t = [Link]() # get total time to execute the functions
#cal_cube(ar)
#cal_sqre(ar)
th1 = [Link](target=cal_sqre, args=(ar, ))
th2 = [Link](target=cal_cube, args=(ar, ))
[Link]()
[Link]()
[Link]()
[Link]()
print(" Total time taking by threads is :", [Link]() - t) # print the total time
print(" Again executing the main thread")
print(" Thread 1 and Thread 2 have finished their execution.")