SlideShare a Scribd company logo
1 of 5
Download to read offline
http://www.tutorialspoint.com/python/python_multithreading .htm Copyright © tutorialspoint.com
PYTHON MULTITHREADED PROGRAMMING
Running severalthreads is similar to running severaldifferent programs concurrently, but withthe following
benefits:
Multiple threads withina process share the same data space withthe mainthread and cantherefore share
informationor communicate witheachother more easily thanif they were separate processes.
Threads sometimes called light-weight processes and they do not require muchmemory overhead; they
care cheaper thanprocesses.
A thread has a beginning, anexecutionsequence, and a conclusion. It has aninstructionpointer that keeps track
of where withinits context it is currently running.
It canbe pre-empted (interrupted)
It cantemporarily be put onhold (also knownas sleeping) while other threads are running - this is called
yielding.
Starting a New Thread:
To spawnanother thread, youneed to callfollowing method available inthread module:
thread.start_new_thread ( function, args[, kwargs] )
This method callenables a fast and efficient way to create new threads inbothLinux and Windows.
The method callreturns immediately and the child thread starts and calls functionwiththe passed list of agrs.
Whenfunctionreturns, the thread terminates.
Here, args is a tuple of arguments; use anempty tuple to callfunctionwithout passing any arguments. kwargs is
anoptionaldictionary of keyword arguments.
Example:
#!/usr/bin/python
import thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
while 1:
pass
Whenthe above code is executed, it produces the following result:
Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009
Althoughit is very effective for low-levelthreading, but the thread module is very limited compared to the newer
threading module.
The Threading Module:
The newer threading module included withPython2.4 provides muchmore powerful, high-levelsupport for
threads thanthe thread module discussed inthe previous section.
The threading module exposes allthe methods of the thread module and provides some additionalmethods:
threading.activeCount(): Returns the number of thread objects that are active.
threading.currentThread(): Returns the number of thread objects inthe caller's thread control.
threading.enumerate(): Returns a list of allthread objects that are currently active.
Inadditionto the methods, the threading module has the Thread class that implements threading. The methods
provided by the Thread class are as follows:
run(): The run() method is the entry point for a thread.
start(): The start() method starts a thread by calling the runmethod.
join([time]): The join() waits for threads to terminate.
isAlive(): The isAlive() method checks whether a thread is stillexecuting.
getName(): The getName() method returns the name of a thread.
setName(): The setName() method sets the name of a thread.
Creating Thread using Threading Module:
To implement a new thread using the threading module, youhave to do the following:
Define a new subclass of the Thread class.
Override the __init__(self [,args]) method to add additionalarguments.
Then, override the run(self [,args]) method to implement what the thread should do whenstarted.
Once youhave created the new Thread subclass, youcancreate aninstance of it and thenstart a new thread by
invoking the start(), whichwillinturncallrun() method.
Example:
#!/usr/bin/python
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
print_time(self.name, self.counter, 5)
print "Exiting " + self.name
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
thread.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print "Exiting Main Thread"
Whenthe above code is executed, it produces the following result:
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2
Synchronizing Threads:
The threading module provided withPythonincludes a simple-to-implement locking mechanismthat willallow you
to synchronize threads. A new lock is created by calling the Lock() method, whichreturns the new lock.
The acquire(blocking) method of the new lock object would be used to force threads to runsynchronously. The
optionalblocking parameter enables youto controlwhether the thread willwait to acquire the lock.
If blocking is set to 0, the thread willreturnimmediately witha 0 value if the lock cannot be acquired and witha 1 if
the lock was acquired. If blocking is set to 1, the thread willblock and wait for the lock to be released.
The release() method of the the new lock object would be used to release the lock whenit is no longer required.
Example:
#!/usr/bin/python
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
Whenthe above code is executed, it produces the following result:
Starting Thread-1
Starting Thread-2
Thread-1: Thu Mar 21 09:11:28 2013
Thread-1: Thu Mar 21 09:11:29 2013
Thread-1: Thu Mar 21 09:11:30 2013
Thread-2: Thu Mar 21 09:11:32 2013
Thread-2: Thu Mar 21 09:11:34 2013
Thread-2: Thu Mar 21 09:11:36 2013
Exiting Main Thread
Multithreaded Priority Queue:
The Queue module allows youto create a new queue object that canhold a specific number of items. There are
following methods to controlthe Queue:
get(): The get() removes and returns anitemfromthe queue.
put(): The put adds itemto a queue.
qsize() : The qsize() returns the number of items that are currently inthe queue.
empty(): The empty( ) returns True if queue is empty; otherwise, False.
full(): the full() returns True if queue is full; otherwise, False.
Example:
#!/usr/bin/python
import Queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print "Starting " + self.name
process_data(self.name, self.q)
print "Exiting " + self.name
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print "%s processing %s" % (threadName, data)
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1
# Create new threads
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# Wait for queue to empty
while not workQueue.empty():
pass
# Notify threads it's time to exit
exitFlag = 1
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
Whenthe above code is executed, it produces the following result:
Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread

More Related Content

What's hot

Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreadingjehan1987
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 

What's hot (20)

Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
multi threading
multi threadingmulti threading
multi threading
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
javathreads
javathreadsjavathreads
javathreads
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Thread
ThreadThread
Thread
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 

Similar to Python multithreading

اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی Mohammad Reza Kamalifard
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxArulmozhivarman8
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptxIrfanShaik98
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
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 BORSANIYAMaulik Borsaniya
 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptxRanjithaM32
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .happycocoman
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptTabassumMaktum
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptTabassumMaktum
 
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
 

Similar to Python multithreading (20)

اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
MULTI THREADING.pptx
MULTI THREADING.pptxMULTI THREADING.pptx
MULTI THREADING.pptx
 
Threads
ThreadsThreads
Threads
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptx
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
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
 
Python programming : Threads
Python programming : ThreadsPython programming : Threads
Python programming : Threads
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
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
 
Multithreading
MultithreadingMultithreading
Multithreading
 

More from Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai

More from Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai (20)

Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area
 
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_SimulationVLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
 
Question Bank: Network Management in Telecommunication
Question Bank: Network Management in TelecommunicationQuestion Bank: Network Management in Telecommunication
Question Bank: Network Management in Telecommunication
 
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdfINTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
 
LRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdfLRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdf
 
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdfNetwork Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
 
Euler Method Details
Euler Method Details Euler Method Details
Euler Method Details
 
Mini Project fo BE Engineering students
Mini Project fo BE Engineering  students  Mini Project fo BE Engineering  students
Mini Project fo BE Engineering students
 
Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students
 
Ballistics Detsils
Ballistics Detsils Ballistics Detsils
Ballistics Detsils
 
VLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant GohatreVLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant Gohatre
 
Cryptography and Network Security
Cryptography and Network SecurityCryptography and Network Security
Cryptography and Network Security
 
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
 
Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...
 
Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...
 
Python overview
Python overviewPython overview
Python overview
 
Python numbers
Python numbersPython numbers
Python numbers
 
Python networking
Python networkingPython networking
Python networking
 
Python modules
Python modulesPython modules
Python modules
 
Python loops
Python loopsPython loops
Python loops
 

Recently uploaded

Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...Call Girls in Nagpur High Profile
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 

Recently uploaded (20)

Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 

Python multithreading

  • 1. http://www.tutorialspoint.com/python/python_multithreading .htm Copyright © tutorialspoint.com PYTHON MULTITHREADED PROGRAMMING Running severalthreads is similar to running severaldifferent programs concurrently, but withthe following benefits: Multiple threads withina process share the same data space withthe mainthread and cantherefore share informationor communicate witheachother more easily thanif they were separate processes. Threads sometimes called light-weight processes and they do not require muchmemory overhead; they care cheaper thanprocesses. A thread has a beginning, anexecutionsequence, and a conclusion. It has aninstructionpointer that keeps track of where withinits context it is currently running. It canbe pre-empted (interrupted) It cantemporarily be put onhold (also knownas sleeping) while other threads are running - this is called yielding. Starting a New Thread: To spawnanother thread, youneed to callfollowing method available inthread module: thread.start_new_thread ( function, args[, kwargs] ) This method callenables a fast and efficient way to create new threads inbothLinux and Windows. The method callreturns immediately and the child thread starts and calls functionwiththe passed list of agrs. Whenfunctionreturns, the thread terminates. Here, args is a tuple of arguments; use anempty tuple to callfunctionwithout passing any arguments. kwargs is anoptionaldictionary of keyword arguments. Example: #!/usr/bin/python import thread import time # Define a function for the thread def print_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % ( threadName, time.ctime(time.time()) ) # Create two threads as follows try: thread.start_new_thread( print_time, ("Thread-1", 2, ) ) thread.start_new_thread( print_time, ("Thread-2", 4, ) ) except: print "Error: unable to start thread" while 1: pass Whenthe above code is executed, it produces the following result: Thread-1: Thu Jan 22 15:42:17 2009 Thread-1: Thu Jan 22 15:42:19 2009 Thread-2: Thu Jan 22 15:42:19 2009
  • 2. Thread-1: Thu Jan 22 15:42:21 2009 Thread-2: Thu Jan 22 15:42:23 2009 Thread-1: Thu Jan 22 15:42:23 2009 Thread-1: Thu Jan 22 15:42:25 2009 Thread-2: Thu Jan 22 15:42:27 2009 Thread-2: Thu Jan 22 15:42:31 2009 Thread-2: Thu Jan 22 15:42:35 2009 Althoughit is very effective for low-levelthreading, but the thread module is very limited compared to the newer threading module. The Threading Module: The newer threading module included withPython2.4 provides muchmore powerful, high-levelsupport for threads thanthe thread module discussed inthe previous section. The threading module exposes allthe methods of the thread module and provides some additionalmethods: threading.activeCount(): Returns the number of thread objects that are active. threading.currentThread(): Returns the number of thread objects inthe caller's thread control. threading.enumerate(): Returns a list of allthread objects that are currently active. Inadditionto the methods, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows: run(): The run() method is the entry point for a thread. start(): The start() method starts a thread by calling the runmethod. join([time]): The join() waits for threads to terminate. isAlive(): The isAlive() method checks whether a thread is stillexecuting. getName(): The getName() method returns the name of a thread. setName(): The setName() method sets the name of a thread. Creating Thread using Threading Module: To implement a new thread using the threading module, youhave to do the following: Define a new subclass of the Thread class. Override the __init__(self [,args]) method to add additionalarguments. Then, override the run(self [,args]) method to implement what the thread should do whenstarted. Once youhave created the new Thread subclass, youcancreate aninstance of it and thenstart a new thread by invoking the start(), whichwillinturncallrun() method. Example: #!/usr/bin/python import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter
  • 3. def run(self): print "Starting " + self.name print_time(self.name, self.counter, 5) print "Exiting " + self.name def print_time(threadName, delay, counter): while counter: if exitFlag: thread.exit() time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() print "Exiting Main Thread" Whenthe above code is executed, it produces the following result: Starting Thread-1 Starting Thread-2 Exiting Main Thread Thread-1: Thu Mar 21 09:10:03 2013 Thread-1: Thu Mar 21 09:10:04 2013 Thread-2: Thu Mar 21 09:10:04 2013 Thread-1: Thu Mar 21 09:10:05 2013 Thread-1: Thu Mar 21 09:10:06 2013 Thread-2: Thu Mar 21 09:10:06 2013 Thread-1: Thu Mar 21 09:10:07 2013 Exiting Thread-1 Thread-2: Thu Mar 21 09:10:08 2013 Thread-2: Thu Mar 21 09:10:10 2013 Thread-2: Thu Mar 21 09:10:12 2013 Exiting Thread-2 Synchronizing Threads: The threading module provided withPythonincludes a simple-to-implement locking mechanismthat willallow you to synchronize threads. A new lock is created by calling the Lock() method, whichreturns the new lock. The acquire(blocking) method of the new lock object would be used to force threads to runsynchronously. The optionalblocking parameter enables youto controlwhether the thread willwait to acquire the lock. If blocking is set to 0, the thread willreturnimmediately witha 0 value if the lock cannot be acquired and witha 1 if the lock was acquired. If blocking is set to 1, the thread willblock and wait for the lock to be released. The release() method of the the new lock object would be used to release the lock whenit is no longer required. Example: #!/usr/bin/python import threading import time class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print "Starting " + self.name
  • 4. # Get lock to synchronize threads threadLock.acquire() print_time(self.name, self.counter, 3) # Free lock to release next thread threadLock.release() def print_time(threadName, delay, counter): while counter: time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 threadLock = threading.Lock() threads = [] # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() # Add threads to thread list threads.append(thread1) threads.append(thread2) # Wait for all threads to complete for t in threads: t.join() print "Exiting Main Thread" Whenthe above code is executed, it produces the following result: Starting Thread-1 Starting Thread-2 Thread-1: Thu Mar 21 09:11:28 2013 Thread-1: Thu Mar 21 09:11:29 2013 Thread-1: Thu Mar 21 09:11:30 2013 Thread-2: Thu Mar 21 09:11:32 2013 Thread-2: Thu Mar 21 09:11:34 2013 Thread-2: Thu Mar 21 09:11:36 2013 Exiting Main Thread Multithreaded Priority Queue: The Queue module allows youto create a new queue object that canhold a specific number of items. There are following methods to controlthe Queue: get(): The get() removes and returns anitemfromthe queue. put(): The put adds itemto a queue. qsize() : The qsize() returns the number of items that are currently inthe queue. empty(): The empty( ) returns True if queue is empty; otherwise, False. full(): the full() returns True if queue is full; otherwise, False. Example: #!/usr/bin/python import Queue import threading import time exitFlag = 0
  • 5. class myThread (threading.Thread): def __init__(self, threadID, name, q): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.q = q def run(self): print "Starting " + self.name process_data(self.name, self.q) print "Exiting " + self.name def process_data(threadName, q): while not exitFlag: queueLock.acquire() if not workQueue.empty(): data = q.get() queueLock.release() print "%s processing %s" % (threadName, data) else: queueLock.release() time.sleep(1) threadList = ["Thread-1", "Thread-2", "Thread-3"] nameList = ["One", "Two", "Three", "Four", "Five"] queueLock = threading.Lock() workQueue = Queue.Queue(10) threads = [] threadID = 1 # Create new threads for tName in threadList: thread = myThread(threadID, tName, workQueue) thread.start() threads.append(thread) threadID += 1 # Fill the queue queueLock.acquire() for word in nameList: workQueue.put(word) queueLock.release() # Wait for queue to empty while not workQueue.empty(): pass # Notify threads it's time to exit exitFlag = 1 # Wait for all threads to complete for t in threads: t.join() print "Exiting Main Thread" Whenthe above code is executed, it produces the following result: Starting Thread-1 Starting Thread-2 Starting Thread-3 Thread-1 processing One Thread-2 processing Two Thread-3 processing Three Thread-1 processing Four Thread-2 processing Five Exiting Thread-3 Exiting Thread-1 Exiting Thread-2 Exiting Main Thread