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

PPTX
Database connectivity in python
PDF
Python programming : Strings
PDF
PPTX
graphics programming in java
PDF
Python-02| Input, Output & Import
PPTX
Basics of Object Oriented Programming in Python
PPTX
PDF
JavaScript - Chapter 12 - Document Object Model
Database connectivity in python
Python programming : Strings
graphics programming in java
Python-02| Input, Output & Import
Basics of Object Oriented Programming in Python
JavaScript - Chapter 12 - Document Object Model

What's hot (20)

PPTX
4. method overloading
PPTX
Method overloading
PPTX
L21 io streams
PPTX
Strings in Java
PPTX
SUBQUERIES.pptx
PDF
A Basic Django Introduction
PPTX
Null values, insert, delete and update in database
PPTX
Constructor overloading & method overloading
PPTX
Java awt (abstract window toolkit)
PPTX
Event handling
PPT
Java awt
PDF
Java String
PPTX
Regular expressions in Python
PDF
Python - gui programming (tkinter)
PPS
Wrapper class
PDF
Java I/o streams
PPT
Active x control
PPTX
Arrays in Java
PDF
StringTokenizer in java
4. method overloading
Method overloading
L21 io streams
Strings in Java
SUBQUERIES.pptx
A Basic Django Introduction
Null values, insert, delete and update in database
Constructor overloading & method overloading
Java awt (abstract window toolkit)
Event handling
Java awt
Java String
Regular expressions in Python
Python - gui programming (tkinter)
Wrapper class
Java I/o streams
Active x control
Arrays in Java
StringTokenizer in java
Ad

Similar to Python programming : Threads (20)

PPT
Python multithreading session 9 - shanmugam
PPTX
Python UNIT-IV Multi Threading B.Tech CSE
PPTX
multithreading to be used in java with good programs.pptx
PDF
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
PPT
Session 7_MULTITHREADING in java example.ppt
PPT
Session 7_MULTITHREADING in java example.ppt
PPTX
Multithreading
PPT
multithreading, creating a thread and life cycle in java.ppt
PPT
Runnable interface.34
DOCX
Class notes(week 9) on multithreading
PPTX
Threading concepts
PPTX
Generators & Decorators.pptx
PPTX
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
PPTX
OOPS object oriented programming UNIT-4.pptx
PPTX
PDF
Class notes(week 9) on multithreading
PPT
Thread model in java
PPTX
Multithreading in Java Object Oriented Programming language
Python multithreading session 9 - shanmugam
Python UNIT-IV Multi Threading B.Tech CSE
multithreading to be used in java with good programs.pptx
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
Multithreading
multithreading, creating a thread and life cycle in java.ppt
Runnable interface.34
Class notes(week 9) on multithreading
Threading concepts
Generators & Decorators.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
OOPS object oriented programming UNIT-4.pptx
Class notes(week 9) on multithreading
Thread model in java
Multithreading in Java Object Oriented Programming language
Ad

More from Emertxe Information Technologies Pvt Ltd (20)

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPT
Teaching material agriculture food technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
A Presentation on Artificial Intelligence
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
KodekX | Application Modernization Development
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Encapsulation theory and applications.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Approach and Philosophy of On baking technology
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Review of recent advances in non-invasive hemoglobin estimation
Teaching material agriculture food technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
The AUB Centre for AI in Media Proposal.docx
Building Integrated photovoltaic BIPV_UPV.pdf
Electronic commerce courselecture one. Pdf
Advanced methodologies resolving dimensionality complications for autism neur...
A Presentation on Artificial Intelligence
Dropbox Q2 2025 Financial Results & Investor Presentation
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
20250228 LYD VKU AI Blended-Learning.pptx
KodekX | Application Modernization Development
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Encapsulation theory and applications.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...

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