Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Unit_III_Part_2_Multithreaded Programming

This document provides an overview of multithreaded programming in Python, detailing concepts such as threads, processes, and the Global Interpreter Lock. It explains how to create and manage threads using the 'threading' module, including examples of single-task and multitasking applications. Additionally, it covers the creation of threads through function-based and class-based methods, along with various example programs demonstrating these concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Unit_III_Part_2_Multithreaded Programming

This document provides an overview of multithreaded programming in Python, detailing concepts such as threads, processes, and the Global Interpreter Lock. It explains how to create and manage threads using the 'threading' module, including examples of single-task and multitasking applications. Additionally, it covers the creation of threads through function-based and class-based methods, along with various example programs demonstrating these concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Department of Computer Science and Engineering (Artificial Intelligence & Machine Learning)

Python Programming – II Year B.Tech II Semester


Course Instructor: Prof.B.Sreenivasu, 9502251564, 9550411738
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

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.

❑ Thread based Multitasking (Multithreading):


➢ Thread is an independent part of execution within program.
➢ Thread performs operation independent of other operations.
➢ Simultaneous execution of more than one thread is called thread based multitasking or
multithreading.
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 2 of 27
❑ Developing Multithreading Applications:
➢ How to work with multithreading or How to develop multithreading applications?
➢ For developing multithreading applications python provides a predefined module called
“threading”. It is default module which comes with python software.
❑ How to create thread?
➢ A thread is created in two ways.
1. Function based / Callable object
2. Class based / Inheritance
➢ “threading” module provides a predefined class “Thread”.
➢ Thread object is used to perform operation of thread.
❑ Creating a Thread:
➢ How to create thread?
➢ Function based:
1. Create a function which is used by thread to perform operation
2. Create thread object by giving input as function
3. Call start method to execute thread
❑ Creating a Thread (Class based thread):
❑ How to create thread?
❑ Class based thread
1. Create a class by inheriting Thread class
2. Override run method of thread class
3. run() method is having an operation performed by thread whenever thread is
executed, it calls run method

❑ Create thread without extending Thread class of threading module


➢ We can create an Independent thread child class that does not inherit from Thread
class of threading module.

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
-----------------------------------------------------------------------------------------------------------------------------------------------------------

# Example python program to demonstrate 'Multithreading concept'


import threading
def even():
for i in range(1,21):
if i%2 ==0:
print(f'{i} is even')

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()

print("Example python program to demonstrate multithreading is executed successfully")

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
-----------------------------------------------------------------------------------------------------------------------------------------------------------

# Example Python Program on Multithreaded Programming


import threading

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

print("Welcome to Multithreaded Programming in Python")


print("To read name of Main Thread appointed by PVM is:
",threading.current_thread().name)

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")

print("Name of the Main Thread appointed by PVM(Python Virtual Maachine) is:


",threading.current_thread().name)
#calling function
CSE()
AIML()
CRA()

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

Welcome to python classWelcome to AIML


Welcome to AIMl class
Welcome to python class
Welcome to AIML
Welcome to AIMl class
Welcome to python class

Welcome to AIMl classWelcome to python class

Welcome to AIMl classWelcome to python class


Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 11 of 27
Welcome to python class

-----------------------------------------------------------------------------------------------------------------------------------------------------------
# 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

print("Hi Welcome to Python programming online classes")


print("Hi BS how are you")
print("Welcome to AIML A & B Students to online session")

print("Name of thread appointed by PVM is: ",threading.current_thread().name)

OUTPUT:

Welcome to AIMLNumber is not even


Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 12 of 27
Welcome to AIML2is even

Welcome to AIMLNumber is not even

Welcome to AIML4is even

Welcome to AIMLNumber is not even

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()

print("Time taken to perform task: ",time.time()-initial_time)

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
-----------------------------------------------------------------------------------------------------------------------------------------------------------

How to Create thread without extending Thread class of threading module:


➢ We can create an Independent thread child class that does not inherit from Thread
class of threading module.
Syntax:
class ClassName:
Statements
obj_name=ClassName()
Thread_Object=Thread(tartget=obj_name.function_name,args=(arg1,arg2,….))
--------------------
Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 16 of 27
Example Program:
# Create thread without extending Thread class of threading module
from threading import Thread
class AIMLB:
def cse(x,y):
if x%2 ==0 and y%2 != 0:
print(f'{x} is even and {y} is odd')
def cse1():
print("I am inside cse1 method")
a1=AIMLB()

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()

print("Time taken to perform task: ",end_time - initial_time)

OUTPUT:

Square numbers: cube numbers:

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()

• This function exits the current thread.

• Instructs a thread to exit.

➢ The _thread module in Python provides low-level primitives for working with threads.

3. _thread.allocate_lock()

• This function creates and returns a new lock object.

• Locks are used to synchronize access to shared resources(global variables, data


structures, file) in multithreaded programs.

4. _thread.get_ident()

• This function returns a unique identifier for the current thread.

5. _thread.stack_size([size])

• This function sets the stack size of the threads created with start_new_thread().

• If no size is provided, it returns the current stack size.

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

#create two functions


def method1():
for i in range(5):
print("Welcome to Microsoft Teams")
time.sleep(1)

def method2():
for i in range(5):
print("Welcome to google meet")
time.sleep(1)

#creating threads to execute functions called 'method1' and 'method2'


_thread.start_new_thread(method1,())
_thread.start_new_thread(method2,())

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

Welcome to google meet


Welcome to Microsoft Teams
Welcome to google meetWelcome to Microsoft Teams

Welcome to google meet


Welcome 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

welcome to AIML Python


Welcome to AIMl java
welcome to AIML Python
Welcome to AIMl java
welcome to AIML Python
Welcome to AIMl java
welcome to AIML Python
Welcome 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

# create a Bus class


class Bus:
def __init__(self):
self.seats = 50
self.lock = threading.Lock()

def reservebus(self, name, seats):


self.lock.acquire()
for i in range(seats):
self.seats = self.seats - 1
print(f"{name} your seats are reserved and Number of available seats: {self.seats}")
self.lock.release()

# 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()

#creating 'reservethread' class objects


t1 = reservethread(bus1, "Akhil", 5)
t2 = reservethread(bus1, "Tarun", 4)
t3 = reservethread(bus1, "Bahu", 2)
t4 = reservethread(bus2, "BS", 3)

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

-----------------------------------------------------------------------------------------------------------------------------------

Concurrent Programming and Global Interpreter lock (GIL)


❑ In python, it is possible to create multiple threads and set them to execute different
parts of program simultaneously. Executing the tasks or parts of a program
simultaneously is called ‘Concurrent programming’.
❑ When more than one thread is running at a time, the data of one thread is
available to another thread. In such cases, there is a possibility that the data may
undergo unwanted manipulations. This happens especially when more than one
thread is acting on the data simultaneously. This will lead to wrong results. This
means PVM is not Thread safe.
❑ Hence PVM uses an Internal global interpreter lock (GIL) that allows only a single
thread to execute at any given moment. GIL does not allow more than thread to
run at a time.
❑ This becomes obstacle to write concurrent programs in python.
❑ Even when there are many processors available in a computer system, The
programmer can use capability of only one processor at a time due to the
restriction imposed by GIL.
❑ However, GIL will not impose this restriction of using only one thread at a time, in
case of normal python programs that take some input and provide output.
❑ GIL will impose this restriction on applications that involve heavy amounts of CPU
processing or those involving multiple processors.

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.

Figure: Shows of GIL in Python.


How to deal with Python’s GIL:
• Choosing a Different Interpreter: Python supports various interpreters, each with its
own characteristics:
• CPython: The standard interpreter, written in C, includes GIL.
• JPython: A Java-based interpreter.
• IronPython: Developed in C#, primarily for .NET environments.
• PyPy: An alternative Python interpreter, implemented in Python, focusing on
performance and efficiency.

-----------------------------------------------------------------------------------------------------------------------------------

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:

# Execution time calculation for a multi-threaded Python program

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

Time taken in multi-thread = 7.794525146484375


Python Programming by Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology (Autonomous) Hyderabad Page 26 of 27
-----------------------------------------------------------------------------------------------------------------------------------

# Execution time calculation for a single-threaded Python program

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()

print("Time taken in single thread = ", endTime - startTime)

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

You might also like