Mahatma Gandhi Mission's College of Engineering and Technology
Department of Computer Science and Engineering (AIML &DS)
Academic Year 2024-25(Even Sem)
Experiment No. 9
Name of Student Shyamdin Prajapati
Roll No 55
DOP DOS Marks/Grade Signature
Aim:Write python programs on threading.
Objective: To study threading using python.
Outcome:Students will be able to understand threading using python.
Theory:
ython Multithreading Multithreading is a threading technique in Python programming to run
P
multiplethreadsconcurrentlybyrapidlyswitchingbetweenthreadswithaCPUhelp(calledcontext
switching). Besides, it allows sharing of its data spacewiththemainthreadsinsideaprocessthat
share information and communication with other threads easier than individual processes.
Multithreading aimstoperformmultipletaskssimultaneously,whichincreasesperformance,speed
and improves the rendering of the application.
Benefits of Multithreading in Python
Following are the benefits to create a multithreaded application in Python, as follows:
1. It ensures effective utilization of computersystem resources.
2. Multithreaded applications are more responsive.
3. It shares resources and its state with sub-threads(child) which makes it more economical.
4. It makes the multiprocessor architecture moreeffective due to similarity.
5. It saves time by executing multiple threadsat the same time.
6. The system does not require too much memoryto store multiple threads.
When to use Multithreading in Python?
I t is a very useful technique for time-saving and improving the performance of an
application. Multithreading allows the programmer to divide application tasks into
subtasks and simultaneously run them in a program. It allows threads to communicate
andshareresourcessuchasfiles,data,andmemorytothesameprocessor.Furthermore,
LAB MANUAL [IV --- Python Lab] Page21
Mahatma Gandhi Mission's College of Engineering and Technology
Department of Computer Science and Engineering (AIML &DS)
Academic Year 2024-25(Even Sem)
itincreasestheuser'sresponsivenesstocontinuerunningaprogramevenifapartofthe
application is the length or blocked
How to achieve multithreading in Python?
here are two main modules of multithreading used to handle threads inPython
T
1. The thread module
2. The threading module
hreadmodulesItisstartedwithPython3,designatedasobsolete,andcanonlybeaccessedwith
T
_threadthat supports backward compatibility.
yntax:thread.start_new_thread(function_name,args[,kwargs])Toimplementthethreadmodule
S
inPython,weneedtoimportathreadmoduleandthendefineafunctionthatperformssomeaction
by setting the target with a variable.
Threading Modules
he threading module is a high-level implementation of multithreading used to deploy an
T
applicationinPythonTousemultithreading,weneedtoimportthethreadingmoduleinthePython
Program.
Methods Description
start() start() method is used to initiate the activity ofa
A
thread.Anditcallsonlyonceforeachthreadsothat
the execution of the thread can begin.
run() run() method is used to define a thread'sactivity
A
and can be overridden by a class that extends the
threads class.
join() join() method is used to block the execution of
A
another code until the thread terminates.
oTarget: It defines the function name that is executedby the thread.
o Args: It defines the arguments that are passed to the target function name.
For example:im
portthreading def print_hello(n):
print("Hello, how old are you ", n)
t1 = threading.Thread( target = print_hello, args =(18, ))
I ntheabovecode,weinvokedtheprint_hello()functionasthetargetparameter.Theprint_hello()
contains one parametern, which passed to theargsparameter.
LAB MANUAL [IV --- Python Lab] Page22
Mahatma Gandhi Mission's College of Engineering and Technology
Department of Computer Science and Engineering (AIML &DS)
Academic Year 2024-25(Even Sem)
3 . Start a new thread: To start a threadinPythonmultithreading,callthethreadclass'sobject.
The start() method can be called once for each thread object; otherwise, it throws an exception
error.
Syntax: t1.start() t2.start()
4 . Joinmethod:Itisajoin()methodusedinthethreadclasstohaltthemainthread's
execution and waits till the complete execution of the thread object. When the thread
object is completed, it starts the execution of the main thread in Python. Joinmethod.py
importthreading
def print_hello(n):
Print("Hello,how old are you? ", n)
T1 = threading.Thread(target = print_hello, args = (20, ))
T1.start()
T1.join()
Print("Thank you")
Output:
Hello, how old are you? 20Thank you
hen the above programisexecuted,thejoin()methodhaltstheexecutionofthemain
W
thread and waits until the thread t1 is completely executed.Oncethet1issuccessfully
executed, the main thread starts its execution.
ote:Ifwedonotusethejoin()method,theinterpretercanexecuteany
N
print statement
insidethePythonprogram.Generally,itexecutesthefirstprintstatement
because the
interpreter executes the lines of codes from the
program's start.
1. Synchronizing Threads in Python
Itisathreadsynchronizationmechanismthatensuresnotwothreadscansimultaneouslyexecutea
particularsegmentinsidetheprogramtoaccessthesharedresources.Thesituationmaybetermedas
criticalsections.Weusearaceconditiontoavoidthecriticalsectioncondition,inwhichtwothreads
do not access resources at the same time.
LAB MANUAL [IV --- Python Lab] Page23
Mahatma Gandhi Mission's College of Engineering and Technology
Department of Computer Science and Engineering (AIML &DS)
Academic Year 2024-25(Even Sem)
Source Code:
f rom threading import Thread
import time
def display():
print("HI")
def display_hello_five_times():
for i in range(5):
t = Thread(target=display)
t.start()
t.join()
display_hello_five_times()
class myTh(Thread):
def run(self):
for i in range(1, 6):
print(i)
t1 = myTh()
t1.start()
t1.join()
class myThread:
def __init__(self, str):
self.str = str
def display(self, x, y):
print(self.str)
print("The args are", x, y)
o bj = myThread("Bye")
t2 = Thread(target=obj.display, args=(2, 3))
t2.start()
t2.join()
def print_even():
for i in range(0, 10, 2):
print(i, end="\t")
time.sleep(0.045)
def print_odd():
for i in range(1, 10, 2):
print(i)
time.sleep(0.05)
p rint("Even\tOdd")
thread1 = Thread(target=print_even)
thread2 = Thread(target=print_odd)
LAB MANUAL [IV --- Python Lab] Page24
Mahatma Gandhi Mission's College of Engineering and Technology
Department of Computer Science and Engineering (AIML &DS)
Academic Year 2024-25(Even Sem)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
InPut and OutPut:
Conclusion: In This way we implement Multithreading in python
LAB MANUAL [IV --- Python Lab] Page25