SlideShare a Scribd company logo
1 of 24
Python Programming
MULTI THREADING
Process
• A process is basically a program in execution. The
execution of a process must progress in a sequential
fashion.
• A process is defined as an entity which represents the
basic unit of work to be implemented in the system.
• A Process Control Block is a data structure maintained by
the Operating System for every process.
Thread
• A thread is a sequence of such instructions within a program
that can be executed independently of other code.
• Thread switching does not need to interact with operating
system.
• While one thread is blocked and waiting, a second thread in the
same task can run.
S.N. Process Thread
1 Process is heavy weight or resource intensive. Thread is light weight, taking lesser resources than a
process.
2 Process switching needs interaction with operating system. Thread switching does not need to interact with operating
system.
3 In multiple processing environments, each process executes
the same code but has its own memory and file resources.
All threads can share same set of open files, child processes.
4 If one process is blocked, then no other process can execute
until the first process is unblocked.
While one thread is blocked and waiting, a second thread in
the same task can run.
5 Multiple processes without using threads use more
resources.
Multiple threaded processes use fewer resources.
6 In multiple processes each process operates independently
of the others.
One thread can read, write or change another thread's data.
Thread LifeCycle
Multithreading
• Running several threads is similar to running several different programs
concurrently.
• Multiple threads within a process share the same data space with the main thread
and can therefore share information or communicate with each other more easily
than if they were separate processes.
• Threads are sometimes called light-weight processes and they do not require much
memory overhead; they are cheaper than processes.
Types of Thread
• User level Thread-It is implemented by user.
• Kernel level Thread-It is implemented by os.
Race condition:
Two or more thread access same piece of data, inconsistent result may arise(because
of order of data access).So we are going for lock system
Threading Module
• Creating Thread Using Threading Module
• define a new subclass of the Thread class.
• Override the __init__(self [,args]) method to add additional arguments.
• Then, override the run(self [,args]) method to implement what the
thread should do when started.
Threading object Methods
• Start()- Begin thread execution.
• Run()- Method defining thread functionality.
• Join()- Suspend until started thread terminates blocks unless timeout is given
• getName() – Return name of thread
• setName()- set name of thread
• isAlive()- Boolean flag indicating whether thread is still running
• isDaemon()- Return Daemon flag of thread.
• SetDaemon()-Used to set the thread as daemon thread.
• Active_count-Return the number of threads currently running.
• Enumerate()-display all the current running thread names.
• Current_Thread()-display the current thread.
Sample Code:
import threading
class mythread(threading.Thread):
def __init__(self,tid,tname):
threading.Thread.__init__(self)
self.id=tid
self.name=tname
def run(self):
print(self.name,self.id)
t1=mythread(1,"THread 1")
t1.start()
t1.join()
t2=mythread(2,"THread 2")
t2.start()
t2.join()
Sample Code
import threading
def f1(name):
print("Thread function1",name)
print(threading.currentThread().getName())
print(threading.currentThread().setName("priy"))
def f2():
print("Thread function2")
print(threading.currentThread().getName())
t=threading.Thread(target=f2)
t1=threading.Thread(target=f1,args=("karthi",))
print(threading.currentThread().getName())
t1.start()
t1.join()
t.start()
Sample Code:
import threading
def f1():
print(threading.active_count())
print(threading.current_thread())
print(threading.enumerate())
for i in range(3):
t=threading.Thread(target=f1)
t.start()
t.join()
Synchronizing Thread
• Locking mechanism that allows us to synchronize threads.
• New lock is created by calling the lock method(returns new lock)
• Acquire(blocking) of new lock object is used to force threads to run synchronously.
• Release() of new lock object is used to release the lock when it is no longer required.
Sample Code
import threading
from time import ctime,sleep
lk=threading.Lock()
def f_daemon(delay,lk):
lk.acquire()
print("thread started",ctime())
sleep(delay)
print("thread exit",ctime())
lk.release()
t=threading.Thread(target=f_daemon,args=(5,lk))
t1=threading.Thread(target=f_daemon,args=(5,lk))
t.start()
t1.start()
Daemon Thread
• Thread running at the background.
• Main program waits until all other threads have completed their
work
Sample Code:
import threading
import time
def fun1():
print("thread1 start")
print("thread1 end")
def fun2():
print("thread2 start")
time.sleep(5)
print("thread2 end")
t1=threading.Thread(target=fun1)
t2=threading.Thread(target=fun2)
t2.setDaemon(True)
t2.start()
t1.start()
print(t2.isDaemon())
print(t1.isDaemon())
print(t2.isAlive())
print(t1.isAlive())
Multithreaded Priority Queue
With the help of Queue module we can create a new queue object that can hold a
specific number of items and threads. Queue module have following method which
is given below.
1. get(): The get() removes and returns an item from the queue.
2.put(): The put adds item to a queue.
3.qsize() : The qsize() returns the number of items that are currently in the queue.
4.empty(): The empty( ) returns True if queue is empty; otherwise, False.
5.full(): the full() returns True if queue is full; otherwise, False.
Creating Queue
import queue
q=queue.Queue(3) #Queue base approach
#q=queue.LifoQueue()#--> stack base approach
for i in range(3):
q.put(i)
print(q.full())
print(q.qsize())
while not q.empty():
print(q.get())
https://www.geeksforgeeks.org/multithreading-python-set-1/
Priority Queue
import queue
q=queue.PriorityQueue()
q.put((2,"two"))
q.put((1,"oner"))
q.put((3,"three"))
q.put((6,"six"))
while not q.empty():
x=q.get()
print(x[0])
print(x[1])
Passing Class as Argument
import queue
class job:
def __init__(self,priority,desc):
self.priority=priority
self.desc=desc
print(priority,desc)
return
q=queue.PriorityQueue()
q.put((3,job(3,"three")))
q.put((2,job(1,"one")))
q.put((4,job(2,"two")))
while not q.empty():
x=q.get()
print("In priority order")
print("your desse",x[1].priority,x[1].desc)
print("your queue eriority",x[0])
•
Multithreaded Priority Queue
import queue
from threading import Thread,Lock
from time import sleep,ctime
class job(Thread):
def __init__(self,ide,q=None):
Thread.__init__(self)
self.ide=ide
self.q=q
def run(self):
process(self.ide,self.q)
lk=Lock()
•
def process(ide,q):
lk.acquire()
print("thread started",ctime())
print("Thread",ide)
print(q)
sleep(3)
print("thread exit",ctime())
lk.release()
list=["kce","kit","it"]
q=queue.PriorityQueue()
q.put((3,job(3,list)))
q.put((2,job(2,list)))
q.put((4,job(4,list)))
while not q.empty():
x=q.get()
x[1].start()
x[1].join()
MULTI THREADING.pptx

More Related Content

Similar to MULTI THREADING.pptx

Multithreading
MultithreadingMultithreading
MultithreadingF K
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 
Java multithreading
Java multithreadingJava multithreading
Java multithreadingMohammed625
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
Multithreaded_Programming_in_Python.pdf
Multithreaded_Programming_in_Python.pdfMultithreaded_Programming_in_Python.pdf
Multithreaded_Programming_in_Python.pdfgiridharsripathi
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreadingTuan Chau
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptxmadan r
 
Understanding Threads in operating system
Understanding Threads in operating systemUnderstanding Threads in operating system
Understanding Threads in operating systemHarrytoye2
 
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Sachintha Gunasena
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptxssuserfcae42
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024kashyapneha2809
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptxramyan49
 

Similar to MULTI THREADING.pptx (20)

Multithreading
MultithreadingMultithreading
Multithreading
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 
MultiThreading in Python
MultiThreading in PythonMultiThreading in Python
MultiThreading in Python
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Multithreaded_Programming_in_Python.pdf
Multithreaded_Programming_in_Python.pdfMultithreaded_Programming_in_Python.pdf
Multithreaded_Programming_in_Python.pdf
 
Java threading
Java threadingJava threading
Java threading
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Understanding Threads in operating system
Understanding Threads in operating systemUnderstanding Threads in operating system
Understanding Threads in operating system
 
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 

MULTI THREADING.pptx

  • 2. Process • A process is basically a program in execution. The execution of a process must progress in a sequential fashion. • A process is defined as an entity which represents the basic unit of work to be implemented in the system. • A Process Control Block is a data structure maintained by the Operating System for every process.
  • 3.
  • 4. Thread • A thread is a sequence of such instructions within a program that can be executed independently of other code. • Thread switching does not need to interact with operating system. • While one thread is blocked and waiting, a second thread in the same task can run.
  • 5.
  • 6. S.N. Process Thread 1 Process is heavy weight or resource intensive. Thread is light weight, taking lesser resources than a process. 2 Process switching needs interaction with operating system. Thread switching does not need to interact with operating system. 3 In multiple processing environments, each process executes the same code but has its own memory and file resources. All threads can share same set of open files, child processes. 4 If one process is blocked, then no other process can execute until the first process is unblocked. While one thread is blocked and waiting, a second thread in the same task can run. 5 Multiple processes without using threads use more resources. Multiple threaded processes use fewer resources. 6 In multiple processes each process operates independently of the others. One thread can read, write or change another thread's data.
  • 8. Multithreading • Running several threads is similar to running several different programs concurrently. • Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes. • Threads are sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes.
  • 9. Types of Thread • User level Thread-It is implemented by user. • Kernel level Thread-It is implemented by os. Race condition: Two or more thread access same piece of data, inconsistent result may arise(because of order of data access).So we are going for lock system
  • 10. Threading Module • Creating Thread Using Threading Module • define a new subclass of the Thread class. • Override the __init__(self [,args]) method to add additional arguments. • Then, override the run(self [,args]) method to implement what the thread should do when started.
  • 11. Threading object Methods • Start()- Begin thread execution. • Run()- Method defining thread functionality. • Join()- Suspend until started thread terminates blocks unless timeout is given • getName() – Return name of thread • setName()- set name of thread • isAlive()- Boolean flag indicating whether thread is still running • isDaemon()- Return Daemon flag of thread. • SetDaemon()-Used to set the thread as daemon thread. • Active_count-Return the number of threads currently running. • Enumerate()-display all the current running thread names. • Current_Thread()-display the current thread.
  • 12. Sample Code: import threading class mythread(threading.Thread): def __init__(self,tid,tname): threading.Thread.__init__(self) self.id=tid self.name=tname def run(self): print(self.name,self.id) t1=mythread(1,"THread 1") t1.start() t1.join() t2=mythread(2,"THread 2") t2.start() t2.join()
  • 13. Sample Code import threading def f1(name): print("Thread function1",name) print(threading.currentThread().getName()) print(threading.currentThread().setName("priy")) def f2(): print("Thread function2") print(threading.currentThread().getName()) t=threading.Thread(target=f2) t1=threading.Thread(target=f1,args=("karthi",)) print(threading.currentThread().getName()) t1.start() t1.join() t.start()
  • 14. Sample Code: import threading def f1(): print(threading.active_count()) print(threading.current_thread()) print(threading.enumerate()) for i in range(3): t=threading.Thread(target=f1) t.start() t.join()
  • 15. Synchronizing Thread • Locking mechanism that allows us to synchronize threads. • New lock is created by calling the lock method(returns new lock) • Acquire(blocking) of new lock object is used to force threads to run synchronously. • Release() of new lock object is used to release the lock when it is no longer required.
  • 16. Sample Code import threading from time import ctime,sleep lk=threading.Lock() def f_daemon(delay,lk): lk.acquire() print("thread started",ctime()) sleep(delay) print("thread exit",ctime()) lk.release() t=threading.Thread(target=f_daemon,args=(5,lk)) t1=threading.Thread(target=f_daemon,args=(5,lk)) t.start() t1.start()
  • 17. Daemon Thread • Thread running at the background. • Main program waits until all other threads have completed their work
  • 18. Sample Code: import threading import time def fun1(): print("thread1 start") print("thread1 end") def fun2(): print("thread2 start") time.sleep(5) print("thread2 end") t1=threading.Thread(target=fun1) t2=threading.Thread(target=fun2) t2.setDaemon(True) t2.start() t1.start() print(t2.isDaemon()) print(t1.isDaemon()) print(t2.isAlive()) print(t1.isAlive())
  • 19. Multithreaded Priority Queue With the help of Queue module we can create a new queue object that can hold a specific number of items and threads. Queue module have following method which is given below. 1. get(): The get() removes and returns an item from the queue. 2.put(): The put adds item to a queue. 3.qsize() : The qsize() returns the number of items that are currently in the queue. 4.empty(): The empty( ) returns True if queue is empty; otherwise, False. 5.full(): the full() returns True if queue is full; otherwise, False.
  • 20. Creating Queue import queue q=queue.Queue(3) #Queue base approach #q=queue.LifoQueue()#--> stack base approach for i in range(3): q.put(i) print(q.full()) print(q.qsize()) while not q.empty(): print(q.get()) https://www.geeksforgeeks.org/multithreading-python-set-1/
  • 22. Passing Class as Argument import queue class job: def __init__(self,priority,desc): self.priority=priority self.desc=desc print(priority,desc) return q=queue.PriorityQueue() q.put((3,job(3,"three"))) q.put((2,job(1,"one"))) q.put((4,job(2,"two"))) while not q.empty(): x=q.get() print("In priority order") print("your desse",x[1].priority,x[1].desc) print("your queue eriority",x[0]) •
  • 23. Multithreaded Priority Queue import queue from threading import Thread,Lock from time import sleep,ctime class job(Thread): def __init__(self,ide,q=None): Thread.__init__(self) self.ide=ide self.q=q def run(self): process(self.ide,self.q) lk=Lock() • def process(ide,q): lk.acquire() print("thread started",ctime()) print("Thread",ide) print(q) sleep(3) print("thread exit",ctime()) lk.release() list=["kce","kit","it"] q=queue.PriorityQueue() q.put((3,job(3,list))) q.put((2,job(2,list))) q.put((4,job(4,list))) while not q.empty(): x=q.get() x[1].start() x[1].join()