SlideShare a Scribd company logo
Threads
Team Emertxe
Introduction
Creating Threads
Creating Threads
Introduction

Python provides ‘Thread’ class of threading module to create the threads

Various methods of creating the threads:

Method-1: Without using the class

Method-2: By creating a sub-class to Thread class

Method-3: Without creating a sub-class to Thread class
Creating Threads
Method-1: Without using class

Step-1:

- Create a thread by creating an object class and pass the function name as target
for the thread
Syntax t = Thread(target = function_name, [args = (arg1, arg2, ...)])
target Represents the function on which thread will act
args Represents the tuple of arguments which are passed to the function

Step-2:

- Start the thread by using start() method
t.start()
Creating Threads
Program-1: No arguments
Creating a thread without using a class
from threading import *
#Create a function
def display():
print("Hello I am running")
#Create a thread and run the function 5 times
for i in range(5):
#Create the thread and specify the function as its target
t = Thread(target = display)
#Run the thread
t.start()
Output:
Hello I am running
Hello I am running
Hello I am running
Hello I am running
Hello I am running
Creating Threads
Program-2: With arguments
Creating a thread without using a class
#To pass arguments to a function and execute it using a thread
from threading import *
#Create a function
def display(str):
print(str)
#Create a thread and run the function for 5 times
for i in range(5):
t = Thread(target = display, args = ("Hello", ))
t.start()
Output:
Hello
Hello
Hello
Hello
Hello
Creating Threads
Method-2: Creating Sub-class to Thread

Step-1: Create a new class by inheriting the Thread class
Example class MyThread(Thread):
MyThread New Class
Thread Base Class

Step-1:

Step-2: Create an Object of MyThread class
t1.join()

Step-3: Wait till the thread completes
t1 = MyThread()
Creating Threads:
Program-1: Creating Sub-class to Thread
Creating a thread by creating the sub-class to thread class
#Creating our own thread
from threading import Thread
#Create a class as sub class to Thread class
class MyThread(Thread):
#Override the run() method of Thread class
def run(self):
for i in range(1, 6):
print(i)
#Create an instance of MyThread class
t1 = MyThread()
#Start running the thread t1
t1.start()
#Wait till the thread completes its job
t1.join()
Output:
1
2
3
4
5
run() method will override the run() method in the Thread class
Creating Threads:
Program-2:
Creating a thread that access the instance variables of a class
#A thread that access the instance variables
from threading import *
#Create a class as sub class to Thread class
class MyThread(Thread):
def __init__(self, str):
Thread.__init__(self)
self.str = str
#Override the run() method of Thread class
def run(self):
print(self.str)
#Create an instance of MyThread class and pass the string
t1 = MyThread("Hello")
#Start running the thread t1
t1.start()
#Wait till the thread completes its job
t1.join()
Output:
Hello
Thread.__init__(self): Calls the constructor of the Thread class
Creating Threads
Method-3: Without creating sub-class to
Thread class

Step-1: Create an independent class

Step-2: Create an Object of MyThread class
t1 = Thread(target = obj.display, args = (1, 2))

Step-3: Create a thread by creating an object to ‘Thread’ class
obj = MyThread(‘Hello’)
Creating Threads
Method-3: Without creating sub-class to
Thread class: Program
Creating a thread without sub-class to thread class
from threading import *
#Create our own class
class MyThread:
#A constructor
def __init__(self, str):
self.str = str
#A Method
def display(self, x, y):
print(self.str)
print("The args are: ", x, y)
#Create an instance to our class and store Hello string
Obj = MyThread("Hello")
#Create a thread to run display method of Obj
t1 = Thread(target = Obj.display, args = (1, 2))
#Run the thread
t1.start()
Output:
Hello
The args are: 1 2
Thread Class Methods
Single Tasking using a Thread
Single Tasking Thread
Introduction

A thread can be employed to execute one task at a time

Example:

Suppose there are three task executed by the thread one after one, then it is
called single tasking
Problem: Preparation of the Tea
Task-1: Boil milk and tea powder for 5 mins
Task-2: Add sugar and boil for 3 mins
Task-3: Filter it and serve
#A method that performs 3 tasks one by one
def prepareTea(self):
self.task1()
self.task2()
self.task3()
Single Tasking Thread
Program
#Single tasking using a single thread
from threading import *
from time import *
#Create our own class
class MyThread:
#A method that performs 3 tasks one by one
def prepareTea(self):
self.task1()
self.task2()
self.task3()
def task1(self):
print("Boil milk and tea powder for 5
mins...", end = '')
sleep(5)
print("Done")
def task2(self):
print("Add sugar and boil for 3 mins...",
end = '')
sleep(3)
print("Done")
def task3(self):
print("Filter and serve...", end = '')
print("Done")
#Create an instance to our class
obj = MyThread()
#Create a thread and run prepareTea method of Obj
t = Thread(target = obj.prepareTea)
t.start()
Multi Tasking using a Multiple Thread
Multi Tasking Threads
Program-1

Using more than one thread is called Multi-threading, used in multi-tasking
#Multitasking using two threads
from threading import *
from time import *
#Create our own class
class Theatre:
#Constructor that accepts a string
def __init__(self, str):
self.str = str
#A method that repeats for 5 tickets
def movieshow(self):
for i in range(1, 6):
print(self.str, ":", i)
sleep(1)
Output:
Run-1:
Cut Ticket : 1
Show chair : 1
Cut Ticket : 2
Show chair : 2
Cut Ticket : 3
Show chair : 3
Cut Ticket : 4
Show chair : 4
Cut Ticket : 5
Show chair : 5
Run-2:
Cut Ticket : 1
Show chair : 1
Cut Ticket : 2
Show chair : 2
Show chair : 3
Cut Ticket : 3
Cut Ticket : 4
Show chair : 4
Cut Ticket : 5
Show chair : 5
#Create two instamces to Theatre class
obj1 = Theatre("Cut Ticket")
obj2 = Theatre("Show chair")
#Create two threads to run movieshow()
t1 = Thread(target = obj1.movieshow)
t2 = Thread(target = obj2.movieshow)
#Run the threads
t1.start()
t2.start()
Race Condition
Multi Tasking Threads
Race-Condition

Using more than one thread is called Multi-threading, used in multi-tasking

Race-condition is a situation where threads are not acting in a expected sequence,
leading to the unreliable output

Race-condition can be avoided by ‘Thread Synchronization’
Multi Tasking Threads
Program-2

Using more than one thread is called Multi-threading, used in multi-tasking
#Multitasking using two threads
from threading import *
from time import *
#Create our own class
class Railway:
#Constrauctor that accepts no. of available berths
def __init__(self, available):
self.available = available
#A method that reserves berth
def reserve(self, wanted):
#Display no. of available births
print("Available no. of berths = ", self.available)
#If available >= wanted, allot the berth
if (self.available >= wanted):
#Find the thread name
name = current_thread().getName()
#Display the berth is allotted for the person
print("%d berths are alloted for %s" % (wanted, name))
#Make time delay so that ticket is printed
sleep(1.5)
#Decrease the number of available berths
self.available -= wanted
else:
#If avaible < wanted, then say sorry
print("Sorry, no berths to allot")
#Create instance to railway class
#Specify only one berth is available
obj = Railway(1)
#Create two threads and specify 1 berth is needed
t1 = Thread(target = obj.reserve, args = (1, ))
t2 = Thread(target = obj.reserve, args = (1, ))
#Give names to the threads
t1.setName("First Person")
t2.setName("Second Person")
#Start running the threads
t1.start()
t2.start()
The output of the above code is not correct. Run multiple times & see the o/p
Thread Synchronization
Thread Synchronization
Introduction
Thread
Synchronization
OR
Thread Safe
When a thread is already acting on an object, preventing any other
thread from acting on the same object is called ‘Thread
Synchronization’ OR ‘Thread Safe’
Synchronized
Object
The object on which the threads are synchronized is called synchronized
object or Mutex(Mutually exclusive lock)
Techniques 1. Locks (Mutex)
2. Semaphores
Thread Synchronization
Mutex
1. Creating the lock
l = Lock()
2. To lock the current object
l.acquire()
3. To unlock or release the object
l.release()
Thread Synchronization
Mutex: Program
#Create our own class
class Railway:
#Constrauctor that accepts no. of available berths
def __init__(self, available):
self.available = available
#Create a lock Object
self.l = Lock()
#A method that reserves berth
def reserve(self, wanted):
#lock the current object
self.l.acquire()
#Display no. of available births
print("Available no. of berths = ", self.available)
#If available >= wanted, allot the berth
if (self.available >= wanted):
#Find the thread name
name = current_thread().getName()
#Display the berth is allotted for the person
print("%d berths are alloted for %s" % (wanted, name))
#Make time delay so that ticket is printed
sleep(1.5)
#Decrease the number of available berths
self.available -= wanted
else:
#If avaible < wanted, then say sorry
print("Sorry, no berths to allot")
#Task is completed, release the lock
self.l.release()
#Create instance to railway class
#Specify only one berth is available
obj = Railway(1)
#Create two threads and specify 1 berth is needed
t1 = Thread(target = obj.reserve, args = (1, ))
t2 = Thread(target = obj.reserve, args = (1, ))
#Give names to the threads
t1.setName("First Person")
t2.setName("Second Person")
#Start running the threads
t1.start()
t2.start()
Thread Synchronization
Semaphore
Semaphore Is an object that provides synchronization based on a counter
Creation l = Semaphore(counter)
#Counter value will be 1 by default
Usage #Acquire the lock
l.acquire()
#Critical Section
#Release the lock
l.release()
Thread Synchronization
Mutex: Program
#Create our own class
class Railway:
#Constrauctor that accepts no. of available berths
def __init__(self, available):
self.available = available
#Create a lock Object
self.l = Semaphore()
#A method that reserves berth
def reserve(self, wanted):
#lock the current object
self.l.acquire()
#Display no. of available births
print("Available no. of berths = ", self.available)
#If available >= wanted, allot the berth
if (self.available >= wanted):
#Find the thread name
name = current_thread().getName()
#Display the berth is allotted for the person
print("%d berths are alloted for %s" % (wanted, name))
#Make time delay so that ticket is printed
sleep(1.5)
#Decrease the number of available berths
self.available -= wanted
else:
#If avaible < wanted, then say sorry
print("Sorry, no berths to allot")
#Task is completed, release the lock
self.l.release()
#Create instance to railway class
#Specify only one berth is available
obj = Railway(1)
#Create two threads and specify 1 berth is needed
t1 = Thread(target = obj.reserve, args = (1, ))
t2 = Thread(target = obj.reserve, args = (1, ))
#Give names to the threads
t1.setName("First Person")
t2.setName("Second Person")
#Start running the threads
t1.start()
t2.start()
Dead Locks
Dead Locks
Introduction
Train
Compartment
bookticket
cancelticket
#Book Ticket thread
lock-1:
lock on train
lock-2:
lock on compartment
#Cancel Ticket thread
lock-2:
lock on compartment
lock-1:
lock on train
When a thread has locked an object and waiting for another object to be released by another thread,
and the other thread is also waiting for the first thread to release the fisrt object, both threads
will continue to wait forever. This condition is called Deadlock
Dead Locks
Program
#Dead lock of threads
from threading import *
#Take two locks
l1 = Lock()
l2 = Lock()
#Create a function for cancelling a ticket
def cancelticket():
l2.acquire()
print("Cancelticket locked compartment")
print("Cancelticket wants to lock on train")
l1.acquire()
print("Cancelticket locked train")
l1.release()
l2.release()
print("Cancellation of ticket is done...")
#Create a function for booking a ticket
def bookticket():
l1.acquire()
print("Bookticket locked train")
print("Bookticket wants to lock on compartment")
l2.acquire()
print("Bookticket locked compartment")
l2.release()
l1.release()
print("Booking ticket done...")
#Create two threads and run them
t1 = Thread(target = bookticket)
t2 = Thread(target = cancelticket)
t1.start()
t2.start()
Dead Locks
Avoiding
Train
Compartment
bookticket
cancelticket
#Book Ticket thread
lock-1:
lock on train
lock-2:
lock on compartment
#Cancel Ticket thread
lock-1:
lock on compartment
lock-2:
lock on train
Dead Locks
Program: Avoiding Deadlocks
#Dead lock of threads
from threading import *
#Take two locks
l1 = Lock()
l2 = Lock()
#Create a function for cancelling a ticket
def cancelticket():
l1.acquire()
print("Cancelticket locked compartment")
print("Cancelticket wants to lock on train")
l2.acquire()
print("Cancelticket locked train")
l2.release()
l1.release()
print("Cancellation of ticket is done...")
#Create a function for booking a ticket
def bookticket():
l1.acquire()
print("Bookticket locked train")
print("Bookticket wants to lock on compartment")
l2.acquire()
print("Bookticket locked compartment")
l2.release()
l1.release()
print("Booking ticket done...")
#Create two threads and run them
t1 = Thread(target = bookticket)
t2 = Thread(target = cancelticket)
t1.start()
t2.start()
Communication between Threads
Threads Communication
Introduction
1, 2, 3, 4
False
Producer Consumer
lst
dataprodover
prod
Threads Communication
Program
from threading import *
from time import *
#Create the consumer class
class Consumer:
def __init__(self, prod):
self.prod = prod
def consume(self):
#sleep for 100ms a s long as dataprodover is False
while self.prod.dataprodover == False:
sleep(0.1)
#Display the content of list when data production is over
print(self.prod.lst)
#Create producer class
class Producer:
def __init__(self):
self.lst = []
self.dataprodover = False
def produce(self):
#create 1 to 10 items and add to the list
for i in range(1, 11):
self.lst.append(i)
sleep(1)
print("Item produced...")
#Inform teh consumer that the data production is completed
self.dataprodover = True
#Create producer object
p = Producer()
#Create consumer object and pass producer object
c = Consumer(p)
#Create producer and consumer threads
t1 = Thread(target = p.produce)
t2 = Thread(target = c.consume)
#Run the threads
t1.start()
t2.start()
Threads Communication
Improving Efficiency

Using notify() and wait()

Using queue
Threads Communication
Improving Efficiency: notify(), wait()
#Create Producer Class
class Producer:
def __init__(self):
self.lst = []
self.cv = Condition()
def produce(self):
#Lock the conditional object
self.cv.acquire()
#Create 1 to 10 items and add to the list
for i in range(1, 11):
self.lst.append(i)
sleep(1)
print("Item produced...")
#Inform the consumer that production is completed
self.cv.notify()
#Release the lock
self.cv.release()
#Create Consumer class
class Consumer:
def __init__(self, prod):
self.prod = prod
def consume(self):
#Get lock on condition object
self.prod.cv.acquire()
#Wait only for 0 seconds after the production
self.prod.cv.wait(timeout = 0)
#Release the lock
self.prod.cv.release()
#Display the contenst of list
print(self.prod.lst)
Threads Communication
Improving Efficiency: Queues
6 5 4 3 2 1
Producer Consumer
q.put()
prod
prod.q.get()
Threads Communication
Improving Efficiency: Queues
#Create Producer class
class Producer:
def __init__(self):
self.q = Queue()
def produce(self):
#Create 1 to 10 items and add to the queue
for i in range(1, 11):
print("Producing item: ", i)
self.q.put(i)
sleep(1)
#Create Consumer class
class Consumer:
def __init__(self, prod):
self.prod = prod
def consume(self):
#Receive 1 to 10 items from the queue
for i in range(1, 11):
print("Receiving item: ", self.prod.q.get(i))
Daemon Threads
Daemon Threads
Introduction
● Sometimes, threads should be run continuosly in the memory
● Example
- Internet Server
- Garbage collector of Python program
● These threads are called Daemon Threads
● To make the thread as Daemon, make
d.daemon = True
Daemon Threads
Program
#To display numbers from 1 to 5 every second
def display():
for i in range(5):
print("Normal thread: ", end = '')
print(i + 1)
sleep(1)
#To display numbers from 1 to 5 every second
def display():
for i in range(5):
print("Normal thread: ", end = '')
print(i + 1)
sleep(1)
#Create a normal thread and attach it to display() and run it
t = Thread(target = display)
t.start()
#Create another thread and attach it to display_time()
d = Thread(target = display_time)
#make the thread daemon
d.daemon = True
#Run the daemon thread
d.start()
THANK YOU

More Related Content

What's hot (20)

Php array
Php arrayPhp array
Php array
Nikul Shah
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Constructors in java
Constructors in javaConstructors in java
Constructors in java
sunilchute1
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
Hitesh-Java
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
Elizabeth alexander
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Java Beans
Java BeansJava Beans
Java Beans
Ankit Desai
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
Medhat Dawoud
 
Introduction to stack
Introduction to stackIntroduction to stack
Introduction to stack
vaibhav2910
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Network programming Using Python
Network programming Using PythonNetwork programming Using Python
Network programming Using Python
Karim Sonbol
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
String in java
String in javaString in java
String in java
Ideal Eyes Business College
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 

Similar to Python programming : Threads (20)

MULTI THREADING.pptx
MULTI THREADING.pptxMULTI THREADING.pptx
MULTI THREADING.pptx
KeerthanaM738437
 
Python multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamPython multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugam
Navaneethan Naveen
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
concurrency
concurrencyconcurrency
concurrency
Jonathan Wagoner
 
Multi Threading.docx
Multi Threading.docxMulti Threading.docx
Multi Threading.docx
manohar25689
 
Multiprocessing.pdf..............,.......
Multiprocessing.pdf..............,.......Multiprocessing.pdf..............,.......
Multiprocessing.pdf..............,.......
Bhaveshmali28
 
Multiprocessing.............,...........
Multiprocessing.............,...........Multiprocessing.............,...........
Multiprocessing.............,...........
Bhaveshmali28
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptx
IrfanShaik98
 
Multithreaded_Programming_in_Python.pdf
Multithreaded_Programming_in_Python.pdfMultithreaded_Programming_in_Python.pdf
Multithreaded_Programming_in_Python.pdf
giridharsripathi
 
MULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptxMULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptx
SaiDhanushM
 
Python multithreaded programming
Python   multithreaded programmingPython   multithreaded programming
Python multithreaded programming
Learnbay Datascience
 
Multithreading by rj
Multithreading by rjMultithreading by rj
Multithreading by rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Do more than one thing at the same time, the Python way
Do more than one thing at the same time, the Python wayDo more than one thing at the same time, the Python way
Do more than one thing at the same time, the Python way
Jaime Buelta
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
MultiThreading in Python
MultiThreading in PythonMultiThreading in Python
MultiThreading in Python
SRINIVAS KOLAPARTHI
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Maulik Borsaniya
 
Concurrency and Python - PyCon MY 2015
Concurrency and Python - PyCon MY 2015Concurrency and Python - PyCon MY 2015
Concurrency and Python - PyCon MY 2015
Boey Pak Cheong
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics module
manikanta361
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
Janu Jahnavi
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
Janu Jahnavi
 
Python multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamPython multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugam
Navaneethan Naveen
 
Multi Threading.docx
Multi Threading.docxMulti Threading.docx
Multi Threading.docx
manohar25689
 
Multiprocessing.pdf..............,.......
Multiprocessing.pdf..............,.......Multiprocessing.pdf..............,.......
Multiprocessing.pdf..............,.......
Bhaveshmali28
 
Multiprocessing.............,...........
Multiprocessing.............,...........Multiprocessing.............,...........
Multiprocessing.............,...........
Bhaveshmali28
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptx
IrfanShaik98
 
Multithreaded_Programming_in_Python.pdf
Multithreaded_Programming_in_Python.pdfMultithreaded_Programming_in_Python.pdf
Multithreaded_Programming_in_Python.pdf
giridharsripathi
 
MULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptxMULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptx
SaiDhanushM
 
Do more than one thing at the same time, the Python way
Do more than one thing at the same time, the Python wayDo more than one thing at the same time, the Python way
Do more than one thing at the same time, the Python way
Jaime Buelta
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Maulik Borsaniya
 
Concurrency and Python - PyCon MY 2015
Concurrency and Python - PyCon MY 2015Concurrency and Python - PyCon MY 2015
Concurrency and Python - PyCon MY 2015
Boey Pak Cheong
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics module
manikanta361
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
Janu Jahnavi
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
Janu Jahnavi
 
Ad

More from Emertxe Information Technologies Pvt Ltd (20)

Career Transition (1).pdf
Career Transition (1).pdfCareer Transition (1).pdf
Career Transition (1).pdf
Emertxe Information Technologies Pvt Ltd
 
10_isxdigit.pdf
10_isxdigit.pdf10_isxdigit.pdf
10_isxdigit.pdf
Emertxe Information Technologies Pvt Ltd
 
01_student_record.pdf
01_student_record.pdf01_student_record.pdf
01_student_record.pdf
Emertxe Information Technologies Pvt Ltd
 
02_swap.pdf
02_swap.pdf02_swap.pdf
02_swap.pdf
Emertxe Information Technologies Pvt Ltd
 
01_sizeof.pdf
01_sizeof.pdf01_sizeof.pdf
01_sizeof.pdf
Emertxe Information Technologies Pvt Ltd
 
07_product_matrix.pdf
07_product_matrix.pdf07_product_matrix.pdf
07_product_matrix.pdf
Emertxe Information Technologies Pvt Ltd
 
06_sort_names.pdf
06_sort_names.pdf06_sort_names.pdf
06_sort_names.pdf
Emertxe Information Technologies Pvt Ltd
 
05_fragments.pdf
05_fragments.pdf05_fragments.pdf
05_fragments.pdf
Emertxe Information Technologies Pvt Ltd
 
04_magic_square.pdf
04_magic_square.pdf04_magic_square.pdf
04_magic_square.pdf
Emertxe Information Technologies Pvt Ltd
 
03_endianess.pdf
03_endianess.pdf03_endianess.pdf
03_endianess.pdf
Emertxe Information Technologies Pvt Ltd
 
02_variance.pdf
02_variance.pdf02_variance.pdf
02_variance.pdf
Emertxe Information Technologies Pvt Ltd
 
01_memory_manager.pdf
01_memory_manager.pdf01_memory_manager.pdf
01_memory_manager.pdf
Emertxe Information Technologies Pvt Ltd
 
09_nrps.pdf
09_nrps.pdf09_nrps.pdf
09_nrps.pdf
Emertxe Information Technologies Pvt Ltd
 
11_pangram.pdf
11_pangram.pdf11_pangram.pdf
11_pangram.pdf
Emertxe Information Technologies Pvt Ltd
 
10_combinations.pdf
10_combinations.pdf10_combinations.pdf
10_combinations.pdf
Emertxe Information Technologies Pvt Ltd
 
08_squeeze.pdf
08_squeeze.pdf08_squeeze.pdf
08_squeeze.pdf
Emertxe Information Technologies Pvt Ltd
 
07_strtok.pdf
07_strtok.pdf07_strtok.pdf
07_strtok.pdf
Emertxe Information Technologies Pvt Ltd
 
06_reverserec.pdf
06_reverserec.pdf06_reverserec.pdf
06_reverserec.pdf
Emertxe Information Technologies Pvt Ltd
 
05_reverseiter.pdf
05_reverseiter.pdf05_reverseiter.pdf
05_reverseiter.pdf
Emertxe Information Technologies Pvt Ltd
 
Ad

Recently uploaded (20)

National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 

Python programming : Threads

  • 4. Creating Threads Introduction  Python provides ‘Thread’ class of threading module to create the threads  Various methods of creating the threads:  Method-1: Without using the class  Method-2: By creating a sub-class to Thread class  Method-3: Without creating a sub-class to Thread class
  • 5. Creating Threads Method-1: Without using class  Step-1:  - Create a thread by creating an object class and pass the function name as target for the thread Syntax t = Thread(target = function_name, [args = (arg1, arg2, ...)]) target Represents the function on which thread will act args Represents the tuple of arguments which are passed to the function  Step-2:  - Start the thread by using start() method t.start()
  • 6. Creating Threads Program-1: No arguments Creating a thread without using a class from threading import * #Create a function def display(): print("Hello I am running") #Create a thread and run the function 5 times for i in range(5): #Create the thread and specify the function as its target t = Thread(target = display) #Run the thread t.start() Output: Hello I am running Hello I am running Hello I am running Hello I am running Hello I am running
  • 7. Creating Threads Program-2: With arguments Creating a thread without using a class #To pass arguments to a function and execute it using a thread from threading import * #Create a function def display(str): print(str) #Create a thread and run the function for 5 times for i in range(5): t = Thread(target = display, args = ("Hello", )) t.start() Output: Hello Hello Hello Hello Hello
  • 8. Creating Threads Method-2: Creating Sub-class to Thread  Step-1: Create a new class by inheriting the Thread class Example class MyThread(Thread): MyThread New Class Thread Base Class  Step-1:  Step-2: Create an Object of MyThread class t1.join()  Step-3: Wait till the thread completes t1 = MyThread()
  • 9. Creating Threads: Program-1: Creating Sub-class to Thread Creating a thread by creating the sub-class to thread class #Creating our own thread from threading import Thread #Create a class as sub class to Thread class class MyThread(Thread): #Override the run() method of Thread class def run(self): for i in range(1, 6): print(i) #Create an instance of MyThread class t1 = MyThread() #Start running the thread t1 t1.start() #Wait till the thread completes its job t1.join() Output: 1 2 3 4 5 run() method will override the run() method in the Thread class
  • 10. Creating Threads: Program-2: Creating a thread that access the instance variables of a class #A thread that access the instance variables from threading import * #Create a class as sub class to Thread class class MyThread(Thread): def __init__(self, str): Thread.__init__(self) self.str = str #Override the run() method of Thread class def run(self): print(self.str) #Create an instance of MyThread class and pass the string t1 = MyThread("Hello") #Start running the thread t1 t1.start() #Wait till the thread completes its job t1.join() Output: Hello Thread.__init__(self): Calls the constructor of the Thread class
  • 11. Creating Threads Method-3: Without creating sub-class to Thread class  Step-1: Create an independent class  Step-2: Create an Object of MyThread class t1 = Thread(target = obj.display, args = (1, 2))  Step-3: Create a thread by creating an object to ‘Thread’ class obj = MyThread(‘Hello’)
  • 12. Creating Threads Method-3: Without creating sub-class to Thread class: Program Creating a thread without sub-class to thread class from threading import * #Create our own class class MyThread: #A constructor def __init__(self, str): self.str = str #A Method def display(self, x, y): print(self.str) print("The args are: ", x, y) #Create an instance to our class and store Hello string Obj = MyThread("Hello") #Create a thread to run display method of Obj t1 = Thread(target = Obj.display, args = (1, 2)) #Run the thread t1.start() Output: Hello The args are: 1 2
  • 15. Single Tasking Thread Introduction  A thread can be employed to execute one task at a time  Example:  Suppose there are three task executed by the thread one after one, then it is called single tasking Problem: Preparation of the Tea Task-1: Boil milk and tea powder for 5 mins Task-2: Add sugar and boil for 3 mins Task-3: Filter it and serve #A method that performs 3 tasks one by one def prepareTea(self): self.task1() self.task2() self.task3()
  • 16. Single Tasking Thread Program #Single tasking using a single thread from threading import * from time import * #Create our own class class MyThread: #A method that performs 3 tasks one by one def prepareTea(self): self.task1() self.task2() self.task3() def task1(self): print("Boil milk and tea powder for 5 mins...", end = '') sleep(5) print("Done") def task2(self): print("Add sugar and boil for 3 mins...", end = '') sleep(3) print("Done") def task3(self): print("Filter and serve...", end = '') print("Done") #Create an instance to our class obj = MyThread() #Create a thread and run prepareTea method of Obj t = Thread(target = obj.prepareTea) t.start()
  • 17. Multi Tasking using a Multiple Thread
  • 18. Multi Tasking Threads Program-1  Using more than one thread is called Multi-threading, used in multi-tasking #Multitasking using two threads from threading import * from time import * #Create our own class class Theatre: #Constructor that accepts a string def __init__(self, str): self.str = str #A method that repeats for 5 tickets def movieshow(self): for i in range(1, 6): print(self.str, ":", i) sleep(1) Output: Run-1: Cut Ticket : 1 Show chair : 1 Cut Ticket : 2 Show chair : 2 Cut Ticket : 3 Show chair : 3 Cut Ticket : 4 Show chair : 4 Cut Ticket : 5 Show chair : 5 Run-2: Cut Ticket : 1 Show chair : 1 Cut Ticket : 2 Show chair : 2 Show chair : 3 Cut Ticket : 3 Cut Ticket : 4 Show chair : 4 Cut Ticket : 5 Show chair : 5 #Create two instamces to Theatre class obj1 = Theatre("Cut Ticket") obj2 = Theatre("Show chair") #Create two threads to run movieshow() t1 = Thread(target = obj1.movieshow) t2 = Thread(target = obj2.movieshow) #Run the threads t1.start() t2.start() Race Condition
  • 19. Multi Tasking Threads Race-Condition  Using more than one thread is called Multi-threading, used in multi-tasking  Race-condition is a situation where threads are not acting in a expected sequence, leading to the unreliable output  Race-condition can be avoided by ‘Thread Synchronization’
  • 20. Multi Tasking Threads Program-2  Using more than one thread is called Multi-threading, used in multi-tasking #Multitasking using two threads from threading import * from time import * #Create our own class class Railway: #Constrauctor that accepts no. of available berths def __init__(self, available): self.available = available #A method that reserves berth def reserve(self, wanted): #Display no. of available births print("Available no. of berths = ", self.available) #If available >= wanted, allot the berth if (self.available >= wanted): #Find the thread name name = current_thread().getName() #Display the berth is allotted for the person print("%d berths are alloted for %s" % (wanted, name)) #Make time delay so that ticket is printed sleep(1.5) #Decrease the number of available berths self.available -= wanted else: #If avaible < wanted, then say sorry print("Sorry, no berths to allot") #Create instance to railway class #Specify only one berth is available obj = Railway(1) #Create two threads and specify 1 berth is needed t1 = Thread(target = obj.reserve, args = (1, )) t2 = Thread(target = obj.reserve, args = (1, )) #Give names to the threads t1.setName("First Person") t2.setName("Second Person") #Start running the threads t1.start() t2.start() The output of the above code is not correct. Run multiple times & see the o/p
  • 22. Thread Synchronization Introduction Thread Synchronization OR Thread Safe When a thread is already acting on an object, preventing any other thread from acting on the same object is called ‘Thread Synchronization’ OR ‘Thread Safe’ Synchronized Object The object on which the threads are synchronized is called synchronized object or Mutex(Mutually exclusive lock) Techniques 1. Locks (Mutex) 2. Semaphores
  • 23. Thread Synchronization Mutex 1. Creating the lock l = Lock() 2. To lock the current object l.acquire() 3. To unlock or release the object l.release()
  • 24. Thread Synchronization Mutex: Program #Create our own class class Railway: #Constrauctor that accepts no. of available berths def __init__(self, available): self.available = available #Create a lock Object self.l = Lock() #A method that reserves berth def reserve(self, wanted): #lock the current object self.l.acquire() #Display no. of available births print("Available no. of berths = ", self.available) #If available >= wanted, allot the berth if (self.available >= wanted): #Find the thread name name = current_thread().getName() #Display the berth is allotted for the person print("%d berths are alloted for %s" % (wanted, name)) #Make time delay so that ticket is printed sleep(1.5) #Decrease the number of available berths self.available -= wanted else: #If avaible < wanted, then say sorry print("Sorry, no berths to allot") #Task is completed, release the lock self.l.release() #Create instance to railway class #Specify only one berth is available obj = Railway(1) #Create two threads and specify 1 berth is needed t1 = Thread(target = obj.reserve, args = (1, )) t2 = Thread(target = obj.reserve, args = (1, )) #Give names to the threads t1.setName("First Person") t2.setName("Second Person") #Start running the threads t1.start() t2.start()
  • 25. Thread Synchronization Semaphore Semaphore Is an object that provides synchronization based on a counter Creation l = Semaphore(counter) #Counter value will be 1 by default Usage #Acquire the lock l.acquire() #Critical Section #Release the lock l.release()
  • 26. Thread Synchronization Mutex: Program #Create our own class class Railway: #Constrauctor that accepts no. of available berths def __init__(self, available): self.available = available #Create a lock Object self.l = Semaphore() #A method that reserves berth def reserve(self, wanted): #lock the current object self.l.acquire() #Display no. of available births print("Available no. of berths = ", self.available) #If available >= wanted, allot the berth if (self.available >= wanted): #Find the thread name name = current_thread().getName() #Display the berth is allotted for the person print("%d berths are alloted for %s" % (wanted, name)) #Make time delay so that ticket is printed sleep(1.5) #Decrease the number of available berths self.available -= wanted else: #If avaible < wanted, then say sorry print("Sorry, no berths to allot") #Task is completed, release the lock self.l.release() #Create instance to railway class #Specify only one berth is available obj = Railway(1) #Create two threads and specify 1 berth is needed t1 = Thread(target = obj.reserve, args = (1, )) t2 = Thread(target = obj.reserve, args = (1, )) #Give names to the threads t1.setName("First Person") t2.setName("Second Person") #Start running the threads t1.start() t2.start()
  • 28. Dead Locks Introduction Train Compartment bookticket cancelticket #Book Ticket thread lock-1: lock on train lock-2: lock on compartment #Cancel Ticket thread lock-2: lock on compartment lock-1: lock on train When a thread has locked an object and waiting for another object to be released by another thread, and the other thread is also waiting for the first thread to release the fisrt object, both threads will continue to wait forever. This condition is called Deadlock
  • 29. Dead Locks Program #Dead lock of threads from threading import * #Take two locks l1 = Lock() l2 = Lock() #Create a function for cancelling a ticket def cancelticket(): l2.acquire() print("Cancelticket locked compartment") print("Cancelticket wants to lock on train") l1.acquire() print("Cancelticket locked train") l1.release() l2.release() print("Cancellation of ticket is done...") #Create a function for booking a ticket def bookticket(): l1.acquire() print("Bookticket locked train") print("Bookticket wants to lock on compartment") l2.acquire() print("Bookticket locked compartment") l2.release() l1.release() print("Booking ticket done...") #Create two threads and run them t1 = Thread(target = bookticket) t2 = Thread(target = cancelticket) t1.start() t2.start()
  • 30. Dead Locks Avoiding Train Compartment bookticket cancelticket #Book Ticket thread lock-1: lock on train lock-2: lock on compartment #Cancel Ticket thread lock-1: lock on compartment lock-2: lock on train
  • 31. Dead Locks Program: Avoiding Deadlocks #Dead lock of threads from threading import * #Take two locks l1 = Lock() l2 = Lock() #Create a function for cancelling a ticket def cancelticket(): l1.acquire() print("Cancelticket locked compartment") print("Cancelticket wants to lock on train") l2.acquire() print("Cancelticket locked train") l2.release() l1.release() print("Cancellation of ticket is done...") #Create a function for booking a ticket def bookticket(): l1.acquire() print("Bookticket locked train") print("Bookticket wants to lock on compartment") l2.acquire() print("Bookticket locked compartment") l2.release() l1.release() print("Booking ticket done...") #Create two threads and run them t1 = Thread(target = bookticket) t2 = Thread(target = cancelticket) t1.start() t2.start()
  • 33. Threads Communication Introduction 1, 2, 3, 4 False Producer Consumer lst dataprodover prod
  • 34. Threads Communication Program from threading import * from time import * #Create the consumer class class Consumer: def __init__(self, prod): self.prod = prod def consume(self): #sleep for 100ms a s long as dataprodover is False while self.prod.dataprodover == False: sleep(0.1) #Display the content of list when data production is over print(self.prod.lst) #Create producer class class Producer: def __init__(self): self.lst = [] self.dataprodover = False def produce(self): #create 1 to 10 items and add to the list for i in range(1, 11): self.lst.append(i) sleep(1) print("Item produced...") #Inform teh consumer that the data production is completed self.dataprodover = True #Create producer object p = Producer() #Create consumer object and pass producer object c = Consumer(p) #Create producer and consumer threads t1 = Thread(target = p.produce) t2 = Thread(target = c.consume) #Run the threads t1.start() t2.start()
  • 35. Threads Communication Improving Efficiency  Using notify() and wait()  Using queue
  • 36. Threads Communication Improving Efficiency: notify(), wait() #Create Producer Class class Producer: def __init__(self): self.lst = [] self.cv = Condition() def produce(self): #Lock the conditional object self.cv.acquire() #Create 1 to 10 items and add to the list for i in range(1, 11): self.lst.append(i) sleep(1) print("Item produced...") #Inform the consumer that production is completed self.cv.notify() #Release the lock self.cv.release() #Create Consumer class class Consumer: def __init__(self, prod): self.prod = prod def consume(self): #Get lock on condition object self.prod.cv.acquire() #Wait only for 0 seconds after the production self.prod.cv.wait(timeout = 0) #Release the lock self.prod.cv.release() #Display the contenst of list print(self.prod.lst)
  • 37. Threads Communication Improving Efficiency: Queues 6 5 4 3 2 1 Producer Consumer q.put() prod prod.q.get()
  • 38. Threads Communication Improving Efficiency: Queues #Create Producer class class Producer: def __init__(self): self.q = Queue() def produce(self): #Create 1 to 10 items and add to the queue for i in range(1, 11): print("Producing item: ", i) self.q.put(i) sleep(1) #Create Consumer class class Consumer: def __init__(self, prod): self.prod = prod def consume(self): #Receive 1 to 10 items from the queue for i in range(1, 11): print("Receiving item: ", self.prod.q.get(i))
  • 40. Daemon Threads Introduction ● Sometimes, threads should be run continuosly in the memory ● Example - Internet Server - Garbage collector of Python program ● These threads are called Daemon Threads ● To make the thread as Daemon, make d.daemon = True
  • 41. Daemon Threads Program #To display numbers from 1 to 5 every second def display(): for i in range(5): print("Normal thread: ", end = '') print(i + 1) sleep(1) #To display numbers from 1 to 5 every second def display(): for i in range(5): print("Normal thread: ", end = '') print(i + 1) sleep(1) #Create a normal thread and attach it to display() and run it t = Thread(target = display) t.start() #Create another thread and attach it to display_time() d = Thread(target = display_time) #make the thread daemon d.daemon = True #Run the daemon thread d.start()