Unit_III_Part_2_Multithreaded Programming
Unit_III_Part_2_Multithreaded Programming
Unit-III: Part-2:
Multithreaded Programming: Introduction, Threads and Processes, Python, Threads, and the
Global Interpreter Lock, Thread Module, Threading Module, Related Modules.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Introduction:
▪ Thread is an independent part of execution within program.
▪ In every python program, if we write a group of statements then these statements are
executed by Python Virtual Machine (PVM) one by one. This execution is called a “Thread”.
▪ Because PVM uses a thread to execute these statements. This means that in every python
program , there is always a thread running internally which is appointed by the PVM to
execute the program statements
▪ For developing multithreading applications python provides a predefined module called
“threading”. It is default module which comes with python software.
Example Program 1:
# A python program to find the currently running thread in a python program.
# Note: every python program is run by 'main thread'
import threading # import a module called 'threading' in python for developing multithreading
#applications
print("........... let us find the name of current thread ...........")
# to find name of the present thread
print("currently running thread: ",threading.current_thread().getName())
# check if it is main thread or not
if threading.current_thread() == threading.main_thread():
print("Current thread is the main thread")
else:
print("Current thread is not main thread")
OUTPUT:
........... let us find the name of current thread ...........
currently running thread: MainThread
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 1 of 27
Current thread is the main thread
----------------------------------------------------------------------------------------------------------------------------------
Multithreading:
➢ Applications are two types
1. Single task applications
2. Multitasking applications
❖ Task is an operation performed by an application.
❑ Single tasking application
• An application which allows one operation at a time is called single tasking
application.
❑ Multitasking application
• An application which allows more than one operation concurrently or
simultaneously is called multitasking application.
Multitasking Applications:
❑ Multitasking applications are two types.
1. Process based multitasking
2. Thread based multitasking
❑ Process based multitasking:
➢ Simultaneous execution of more than one program or process is called process-based
multitasking. It is used for developing operating systems.
• Key point: Advantage of multitasking applications is utilizing CPU idle time.
class ClassName:
Statements
obj_name=ClassName()
Thread_Object=threading.Thread(tartget=obj_name.function_name,args=(arg1,arg2,….))
-----------------------------------------------------------------------------------------------------------------------------------------------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 3 of 27
# Python program to demonstrate Single task Application
#creating functions
def fun1():
print("inside fun1")
def fun2():
print("inside fun2")
def fun3():
print("inside fun3")
#calling functions
fun1()
fun2()
fun3()
Output:
inside fun1
inside fun2
inside fun3
-----------------------------------------------------------------------------------------------------------------------------------------------------------
def odd():
for i in range(1,21):
if i%2 != 0:
print(f'{i} is odd')
# creating thread objects from pre-defined class called 'Thread' in threading module
t1=threading.Thread(target=even)
t2=threading.Thread(target=odd)
t1.start()
t2.start()
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 4 of 27
OUTPUT:
2 is even1 is odd
4 is even
6 is even
8 is even3 is odd
5 is odd
7 is odd10 is even
9 is odd12 is even
11 is odd14 is even
13 is odd16 is even
15 is odd18 is even
17 is odd20 is even
19 is odd
-----------------------------------------------------------------------------------------------------------------------------------------------------------
# Important Example:
import threading
import time
def Hello():
for i in range(5):
print("Hello")
def Hi():
for i in range(5):
print("Hi")
def Sreenivasu():
for i in range(5):
print("BS")
print("Python is an OOP")
t1=threading.Thread(target=Hello)
t2=threading.Thread(target=Hi)
t3=threading.Thread(target=Sreenivasu)
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 5 of 27
OUTPUT:
Python is an OOP
HelloHiBS
HelloHiBS
HelloHiBS
HelloHiBS
HelloHiBS
-----------------------------------------------------------------------------------------------------------------------------------------------------------
#------------python program to demonstrate multithreading-------------------
import time
import threading
def fun1():
for i in range(10):
print("inside function1")
time.sleep(1)
def fun2(a,b):
for i in range(10):
div=a/b
print("division of a and b is: ",div)
time.sleep(1)
t1=threading.Thread(target=fun1)
t2=threading.Thread(target=fun2,args=(20,4))
t1.start()
t2.start()
t1.join()
t2.join()
OUTPUT:
inside function1division of a and b is:
5.0
inside function1
division of a and b is: 5.0
inside function1division of a and b is:
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 6 of 27
5.0
inside function1
division of a and b is: 5.0
inside function1
division of a and b is: 5.0
inside function1
division of a and b is: 5.0
inside function1
division of a and b is: 5.0
inside function1
division of a and b is: 5.0
inside function1
division of a and b is: 5.0
inside function1
division of a and b is: 5.0
Example python program to demonstrate multithreading is executed successfully
-----------------------------------------------------------------------------------------------------------------------------------------------------------
def palindrome(string):
str2=string[::-1]
if string == str2:
print("String is palindrome")
else:
print("String is not palindrome")
def fun1():
for i in range(7):
print("I am inside a fucntion1")
#creating thread objects using pre-defined class called 'Thread' defined in 'threading'
module
t1=threading.Thread(target=palindrome,args=("Sreenivasu",))
t2=threading.Thread(target=fun1)
t1.start()
t2.start()
t1.join() # let thread t1 to fininsh its job
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 7 of 27
t2.join() # let thread t2 to finish its job
OUTPUT:
String is not palindrome
Welcome to Multithreaded Programming in Python I am inside a fucntion1
I am inside a fucntion1
I am inside a fucntion1
I am inside a fucntion1
I am inside a fucntion1
I am inside a fucntion1
I am inside a fucntion1
To read name of Main Thread appointed by PVM is: MainThread
-----------------------------------------------------------------------------------------------------------------------------------------------------------
Key Note:
❑ Threads are scheduled by thread scheduler provided by PVM (Python Virtual Machine).
There are different thread scheduling methods exists.
➢ Time slicing
➢ Round Robin
-----------------------------------------------------------------------------------------------------------------------------------------------------------
#Example Program:
# creating thread by inheriting Thread class
import threading
class EvenThread(threading.Thread):
def __init__(self):
super().__init__()
def run(self):
for num in range(1,21):
if num%2==0:
print(f'Even {num}')
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 8 of 27
class OddThread(threading.Thread):
def __init__(self):
super().__init__()
def run(self):
for num in range(1,21):
if num%2!=0:
print(f'Odd {num}')
t1=EvenThread()
t2=OddThread()
t1.start()
t2.start()
OUTPUT:
Even 2Odd 1
Even 4Odd 3
Even 6Odd 5
Even 8Odd 7
Even 10Odd 9
Even 12Odd 11
Even 14Odd 13
Even 16Odd 15
Even 18Odd 17
Even 20Odd 19
-----------------------------------------------------------------------------------------------------------------------------------------------------------
# Python program to demonstrate single task application
import threading
def CSE():
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 9 of 27
for i in range(5):
print("Welcome to AIML")
def AIML():
for i in range(7):
print("Welcome to python class")
def CRA():
for i in range(5):
print("Welcome to AIMl class")
OUTPUT:
Name of the Main Thread appointed by PVM(Python Virtual Maachine) is: MainThread
Welcome to AIML
Welcome to AIML
Welcome to AIML
Welcome to AIML
Welcome to AIML
Welcome to python class
Welcome to python class
Welcome to python class
Welcome to python class
Welcome to python class
Welcome to python class
Welcome to python class
Welcome to AIMl class
Welcome to AIMl class
Welcome to AIMl class
Welcome to AIMl class
Welcome to AIMl class
-----------------------------------------------------------------------------------------------------------------------------------------------------------
# Python program to demonstrate Thread based Multitasking ( Multithreading)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 10 of 27
# Creating threads ( function based)
import threading
def CSE():
for i in range(5):
print("Welcome to AIML")
def AIML():
for i in range(7):
print("Welcome to python class")
def CRA():
for i in range(5):
print("Welcome to AIMl class")
#creating thread objects using Thread class which pre-defined class in threading module
t1=threading.Thread(target=CSE)
t2=threading.Thread(target=AIML)
t3=threading.Thread(target=CRA)
t1.start()
t2.start()
t3.start()
OUTPUT:
Welcome to AIML
Welcome to AIML
Welcome to python classWelcome to AIMl class
Welcome to AIML
-----------------------------------------------------------------------------------------------------------------------------------------------------------
# python program to demonstrate creating class based thread and to demonstrate
# thread based multitasking.
import threading
class CSEAIML(threading.Thread): # creating custom thread class called CSEAIML
def run(self):
for i in range(5):
print("Welcome to AIML")
class MyThread(threading.Thread):
def run(self):
for i in range(1,10):
if i%2 == 0:
print(f"{i}is even")
else:
print("Number is not even")
# creating instance (thread objects) of custom thread classes called 'CSEAIML' and
'MyThread'
t1=CSEAIML()
t2=MyThread()
t1.start()
t2.start()
t1.join() # let thread t1 to finish its job
t2.join() # let thread t2 to finish its job
OUTPUT:
6is even
Number is not even
8is even
Number is not even
Hi Welcome to Python programming online classes
Hi BS how are you
Welcome to AIML A & B Students to online session
Name of thread appointed by PVM is: MainThread
-----------------------------------------------------------------------------------------------------------------------------------------------------------
# Python program to print the total time taken to perform specified tasks
# with out Threads
import time
def calc_square(list):
print("Square numbers: ")
for num in list:
print("Square: ",num*num)
time.sleep(1)
def calc_cube(list):
print("cube numbers: ")
for num in list:
print("Cube: ",num*num*num)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 13 of 27
time.sleep(1)
initial_time=time.time()
list=[1,2,3,4,5]
calc_square(list)
calc_cube(list)
print("Time taken to perform task: ",time.time()-initial_time)
OUTPUT:
Square of a number is: 1
Square of a number is: 4
Square of a number is: 9
Square of a number is: 16
Square of a number is: 25
cube of a number is: 1
cube of a number is: 8
cube of a number is: 27
cube of a number is: 64
cube of a number is: 125
Time taken by the processor to perform specified task is: 10.148541688919067
-----------------------------------------------------------------------------------------------------------------------------------------------------------
# Python program to print the total time taken to perform specified tasks
# with Threads
import time
import threading
def calc_square(list):
print("Square numbers: ")
for num in list:
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 14 of 27
print("Square: ",num*num)
time.sleep(1)
def calc_cube(list):
print("cube numbers: ")
for num in list:
print("Cube: ",num*num*num)
time.sleep(1)
initial_time=time.time()
list=[1,2,3,4,5]
t1=threading.Thread(target=calc_square,args=(list,))
t2=threading.Thread(target=calc_cube,args=(list,))
t1.start()
t2.start()
t1.join()
t2.join()
OUTPUT:
Square numbers:
cube numbers: Square: 1
Cube: 1
Square: 4
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 15 of 27
Cube: 8
Square: 9
Cube: 27
Square: 16
Cube: 64
Square: 25Cube:
125
Time taken to perform task: 5.079465389251709
-----------------------------------------------------------------------------------------------------------------------------------------------------------
#python program to print thread name
import threading
class Mythread(threading.Thread):
pass
t1=Mythread()
print(t1.name)
OUTPUT:
Thread-1
-----------------------------------------------------------------------------------------------------------------------------------------------------------
t1=Thread(target=a1.cse,args=(2,3))
t2=Thread(target=a1.cse1)
t1.start()
t2.start()
print("Hi vacation is completed")
OUTPUT:
--------------------------------------------------------------------------------------------------------------------------------
# Python program to print the total time taken to perform specified tasks
# with Threads
import time
import threading
def calc_square(list):
print("Square numbers: ")
for num in list:
print("Square: ",num*num)
time.sleep(1)
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 17 of 27
def calc_cube(list):
print("cube numbers: ")
for num in list:
print("Cube: ",num*num*num)
time.sleep(1)
initial_time=time.time()
list=[1,2,3,4,5]
t1=threading.Thread(target=calc_square,args=(list,))
t2=threading.Thread(target=calc_cube,args=(list,))
t1.start()
t2.start()
t1.join()
t2.join()
end_time=time.time()
OUTPUT:
Square: Cube: 11
Square: Cube: 48
Square: 9
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 18 of 27
Cube: 27
Square: Cube: 16
64
Square: 25
Cube: 125
Time taken to perform task: 5.128380298614502
-----------------------------------------------------------------------------------------------------------------------------------
Key Note: Every python program is executed within PVM process as a thread. The default
thread created by PVM is MainThread.
-----------------------------------------------------------------------------------------------------------------------------------
Thread module in python for Multithreading
▪ ‘thread’ module in python re-named as ‘_thread’ in python 3
➢ The _thread module in Python provides low-level functioning for working with
threads.
Important functions in ‘_thread’ module:
1. _thread.start_new_thread(function, args)
• This function starts a new thread by invoking the function with the arguments(args).
2. _thread.exit()
➢ The _thread module in Python provides low-level primitives for working with threads.
3. _thread.allocate_lock()
4. _thread.get_ident()
5. _thread.stack_size([size])
• This function sets the stack size of the threads created with start_new_thread().
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 19 of 27
Key note:
❑ These are the basic functions provided by the _thread module.
❑ However, for most of the applications, the threading module is preferred over _thread
as it provides a higher-level interface for working with threads, including thread
synchronization mechanisms and more advanced threading features.
-----------------------------------------------------------------------------------------------------------------------------------
# python program to demonstrate usage of BIMs in thread module in
# creating / developing multithreading applications
import _thread
import time
def method2():
for i in range(5):
print("Welcome to google meet")
time.sleep(1)
OUTPUT:
Welcome to google meetWelcome to Microsoft Teams
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 20 of 27
Welcome to google meetWelcome to Microsoft Teams
-----------------------------------------------------------------------------------------------------------------------------------
# Example python program using ‘_thread’ module
import time
import _thread
def function1():
for i in range(5):
print("welcome to AIML Python")
time.sleep(1)
def function2():
for i in range(5):
print("Welcome to AIMl java")
time.sleep(1)
try:
_thread.start_new_thread(function1,())
_thread.start_new_thread(function2,())
except Exception as e:
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 21 of 27
print("Error: unable to start threads")
OUTPUT:
welcome to AIML PythonWelcome to AIMl java
-----------------------------------------------------------------------------------------------------------------------------------
Thread Synchronization or Locking:
➢ Synchronization is process of acquiring the lock on the object.
➢ When more than one thread operates on shared resource, allowing only one thread
to perform operation is called “synchronization”.
➢ Thread synchronization allows thread safe applications.
➢ It avoids logical errors.
➢ Thread synchronization is a mechanism used in multithreading to ensure that multiple
threads access shared resources (such as variables, data structures, or files) in a
coordinated manner, avoiding conflicts and maintaining consistency.
➢ In a multithreaded programming, where multiple threads execute concurrently,
synchronization becomes essential to prevent race conditions, data corruption, and
other concurrency-related issues.
➢ The threading module in Python includes locking mechanism that allows you to
synchronize threads. A new lock is created by calling the Lock() method, which
returns the new lock.
Syntax:
def <method-name>():
lock.acquire()
statement1
statement2
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 22 of 27
statement3
lock.release()
# Python program to implement bus reservation system using threading module in python
# (using multithreading concept in python)
import threading
# defining a child thread class (custom thread class) called 'reservethread' inheriting
#Thread class of threading module
class reservethread(threading.Thread):
def __init__(self, bus, name, seats):
super().__init__()
self.bus = bus
self.name = name
self.seats = seats
def run(self):
self.bus.reservebus(self.name, self.seats)
# creating Bus class objects
bus1 = Bus()
bus2=Bus()
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 23 of 27
# start the threads
t1.start()
t2.start()
t3.start()
t4.start()
OUTPUT:
Akhil your seats are reserved and Number of available seats: 45
BS your seats are reserved and Number of available seats: 47
Tarun your seats are reserved and Number of available seats: 41
Bahu your seats are reserved and Number of available seats: 39
-----------------------------------------------------------------------------------------------------------------------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 24 of 27
❑ The Python Global Interpreter Lock or GIL, in simple words, is a mutex (or a lock) that
allows only one thread to hold the control of the Python interpreter. This means that
only one thread can be in a state of execution at any point of time.
❑ GIL in Python is a mutex that gives the control of Python interpreter only to a single
thread at a time.
-----------------------------------------------------------------------------------------------------------------------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 25 of 27
Example python programs to understand GIL in Python:
import time
from threading import Thread
def calculateSum(n):
sum = 0
for i in range(n):
sum += i
print(sum)
n = 100000000
T1 = Thread(target=calculateSum, args=(n,))
T2 = Thread(target=calculateSum, args=(n,))
startTime = time.time()
T1.start()
T2.start()
T1.join()
T2.join()
endTime = time.time()
print("Time taken in multi-thread = ", endTime - startTime)
OUTPUT:
49999999500000004999999950000000
import time
def calculateSum(n):
sum = 0
for i in range(n):
sum += i
print(sum)
n = 100000000
startTime = time.time()
calculateSum(n)
endTime = time.time()
OUTPUT:
4999999950000000
Time taken in single thread = 3.918248414993286
-----------------------------------------------------------------------------------------------------------------------------------
*****
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 27 of 27