SlideShare a Scribd company logo
6
Most read
8
Most read
12
Most read
Threads in python
Disclaimer: This presentation is prepared by trainees of
baabtra as a part of mentoring program. This is not official
document of baabtra –Mentoring Partner
Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt .
Ltd
Typing Speed
Week

Target

Achieved

1

25

23

2

30

26

3

30

28
Jobs Applied
#

Company

Designation

Applied Date

1

ioss

Php developer

2

sesame

Python programmer

Aug 26

3

mobileconception

programmer

Aug 24

Current
Status
Threads in python
shafeeque
●

shafeequemonp@gmail.com

●

www.facebook.com/shafeequemonppambodan

●

twitter.com/shafeequemonp

●

in.linkedin.com/in/shafeequemonp

●

9809611325
Introduction
What are threads?
●

●

A thread is a light-weight process
A thread of execution is the smallest sequence of programmed
instructions that can be managed independently by an operating
system scheduler
process
Time

A process with two threads of execution on a single processor.
●

for example copying a file and showing the progress, or playing
a music while showing some pictures as a slideshow, or a
listener handles cancel event for aborting a file copy operation
●

Multithreading generally occurs by time- division multiplexing.

●

The processor switches between different threads

●

●

●

●

●

On a multiprocessor or multi-core system, threads can be truly 
concurrent, with every processor or core executing a separate thread 
simultaneously.
Many modern operating systems directly support both time-sliced and 
multiprocessor threading with a process scheduler.
The scheduler is an operating system module that selects the next 
jobs to be admitted into the system and the next process to run.
The kernel of an operating system allows programmers to manipulate 
threads via the system call interface
Multi-threading is a widespread programming and execution model 
that allows multiple threads to exist within the context of a single 
process
The following diagram shows how the application does that.
Python Threading:
●

●

●

A thread has a beginning, an execution sequence, and a conclusion. It has an instruction 
pointer that keeps track of where within its context it is currently running.
    it can be pre-empted (interrupted)
    It can temporarily be put on hold (also known as sleeping) while other threads are running  
   this is called yielding.

Starting a New Thread:
To spawn another thread, you need to call following method available in thread module:
thread.start_new_thread ( function, args[, kwargs] )
●

●

The method call returns immediately and the child thread starts and calls function with the 
passed list of args. When function returns, the thread terminates.
Here, args is a tuple of arguments; use an empty tuple to call function without passing any 
arguments. kwargs is an optional dictionary 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
When the above code is executed, it produces the following result:

Thread-1: Tue Sep  3 10:10:38 2013
Thread-2: Tue Sep  3 10:10:40 2013
Thread-1: Tue Sep  3 10:10:40 2013
Thread-1: Tue Sep  3 10:10:42 2013
Thread-1: Tue Sep  3 10:10:44 2013
Thread-2: Tue Sep  3 10:10:44 2013
Thread-1: Tue Sep  3 10:10:46 2013
Thread-2: Tue Sep  3 10:10:48 2013
Thread-2: Tue Sep  3 10:10:52 2013
Thread-2: Tue Sep  3 10:10:56 2013
The Threading Module:
●

●

The newer threading module included with Python 2.4 provides much more 
powerful, high-level support for threads than the thread module discussed in the 
previous section.
The threading module exposes all the methods of the thread module and provides 
some additional methods:
threading.activeCount(): Returns the number of thread 
objects that are active.
threading.currentThread(): Returns the number of thread 
objects in the caller's thread control.
threading.enumerate(): Returns a list of all thread objects 
that are currently active.
In addition to 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 run method.
join([time]): The join() waits for threads to terminate.
isAlive(): The isAlive() method checks whether a thread is still executing.
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, you have to do the
following:
●

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.

Once you have created the new Thread subclass, you can create an instance of it and
then start a new thread by invoking the start(), which will in turn call run() 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"
When the above code is executed, it
produces the following result:
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21
Thread-1: Thu Mar 21
Thread-2: Thu Mar 21
Thread-1: Thu Mar 21
Thread-1: Thu Mar 21
Thread-2: Thu Mar 21
Thread-1: Thu Mar 21
Exiting Thread-1
Thread-2: Thu Mar 21
Thread-2: Thu Mar 21
Thread-2: Thu Mar 21
Exiting Thread-2

09:10:03
09:10:04
09:10:04
09:10:05
09:10:06
09:10:06
09:10:07

2013
2013
2013
2013
2013
2013
2013

09:10:08 2013
09:10:10 2013
09:10:12 2013
Synchronizing Threads:
●

●

●

●

●

●

The threading module provided with Python includes a simple-toimplement locking mechanism that will allow you to synchronize threads
A new lock is created by calling the Lock() method, which returns the new
lock.
The acquire(blocking) method of the new lock object would be used to
force threads to run synchronously
The optional blocking parameter enables you to control whether the
thread will wait to acquire the lock.
If blocking is set to 0, the thread will return immediately with a 0 value if
the lock cannot be acquired and with a 1 if the lock was acquired. If
blocking is set to 1, the thread will block and wait for the lock to be
released.
The release() method of the the new lock object would be used to release
the lock when it 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"
When the above code is executed, it produces the
following result:
Starting Thread-1
Starting Thread-2
Thread-1: Thu Mar 21
Thread-1: Thu Mar 21
Thread-1: Thu Mar 21
Thread-2: Thu Mar 21
Thread-2: Thu Mar 21
Thread-2: Thu Mar 21
Exiting Main Thread

09:11:28
09:11:29
09:11:30
09:11:32
09:11:34
09:11:36

2013
2013
2013
2013
2013
2013
If this presentation helped you, please visit our page facebook.com/baabtra and
like it.

Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550

Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com

NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550

More Related Content

PPTX
Basic Python Introduction Lecture 1.pptx
Aditya Patel
 
PDF
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
Edureka!
 
PPT
1.python interpreter and interactive mode
ManjuA8
 
PPTX
Iterarators and generators in python
Sarfaraz Ghanta
 
PDF
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
PDF
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
PDF
File and directories in python
Lifna C.S
 
PDF
Python - object oriented
Learnbay Datascience
 
Basic Python Introduction Lecture 1.pptx
Aditya Patel
 
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
Edureka!
 
1.python interpreter and interactive mode
ManjuA8
 
Iterarators and generators in python
Sarfaraz Ghanta
 
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
File and directories in python
Lifna C.S
 
Python - object oriented
Learnbay Datascience
 

What's hot (20)

ODP
Python Modules
Nitin Reddy Katkam
 
PPSX
Modules and packages in python
TMARAGATHAM
 
PPTX
Python: Modules and Packages
Damian T. Gordon
 
PPTX
Packages In Python Tutorial
Simplilearn
 
PPTX
Threads in JAVA
Haldia Institute of Technology
 
PPTX
Regular expressions in Python
Sujith Kumar
 
PPT
Chapter 13 - Recursion
Adan Hubahib
 
PDF
File handling in Python
BMS Institute of Technology and Management
 
PPTX
Chapter 05 classes and objects
Praveen M Jigajinni
 
PPTX
Inner classes in java
PhD Research Scholar
 
PPTX
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
PDF
Java threads
Prabhakaran V M
 
PPTX
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
PDF
C++ Standard Template Library
Ilio Catallo
 
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
PPTX
File handling in Python
Megha V
 
PPTX
Templates in c++
ThamizhselviKrishnam
 
PPTX
this keyword in Java.pptx
ParvizMirzayev2
 
PPT
Function overloading(c++)
Ritika Sharma
 
PDF
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Python Modules
Nitin Reddy Katkam
 
Modules and packages in python
TMARAGATHAM
 
Python: Modules and Packages
Damian T. Gordon
 
Packages In Python Tutorial
Simplilearn
 
Regular expressions in Python
Sujith Kumar
 
Chapter 13 - Recursion
Adan Hubahib
 
Chapter 05 classes and objects
Praveen M Jigajinni
 
Inner classes in java
PhD Research Scholar
 
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
Java threads
Prabhakaran V M
 
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
C++ Standard Template Library
Ilio Catallo
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
File handling in Python
Megha V
 
Templates in c++
ThamizhselviKrishnam
 
this keyword in Java.pptx
ParvizMirzayev2
 
Function overloading(c++)
Ritika Sharma
 
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Ad
Ad

Similar to Threads in python (20)

PPT
Python multithreading session 9 - shanmugam
Navaneethan Naveen
 
PPTX
MULTI THREADING.pptx
KeerthanaM738437
 
PDF
Python multithreaded programming
Learnbay Datascience
 
PDF
concurrency
Jonathan Wagoner
 
PDF
Multithreaded_Programming_in_Python.pdf
giridharsripathi
 
PDF
Python programming : Threads
Emertxe Information Technologies Pvt Ltd
 
PPTX
Python UNIT-IV Multi Threading B.Tech CSE
SrinuTelugu
 
PPTX
Generators & Decorators.pptx
IrfanShaik98
 
PPTX
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Maulik Borsaniya
 
PPTX
MULTI-THREADING in python appalication.pptx
SaiDhanushM
 
PDF
Python multithreading
Janu Jahnavi
 
PPTX
Python multithreading
Janu Jahnavi
 
PDF
MultiThreading in Python
SRINIVAS KOLAPARTHI
 
DOCX
Multi Threading.docx
manohar25689
 
PDF
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
PDF
Concurrency and Python - PyCon MY 2015
Boey Pak Cheong
 
PPTX
multithreadingppt.pptx
FardeenAzhar
 
PPTX
Mathemetics module
manikanta361
 
Python multithreading session 9 - shanmugam
Navaneethan Naveen
 
MULTI THREADING.pptx
KeerthanaM738437
 
Python multithreaded programming
Learnbay Datascience
 
concurrency
Jonathan Wagoner
 
Multithreaded_Programming_in_Python.pdf
giridharsripathi
 
Python programming : Threads
Emertxe Information Technologies Pvt Ltd
 
Python UNIT-IV Multi Threading B.Tech CSE
SrinuTelugu
 
Generators & Decorators.pptx
IrfanShaik98
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Maulik Borsaniya
 
MULTI-THREADING in python appalication.pptx
SaiDhanushM
 
Python multithreading
Janu Jahnavi
 
Python multithreading
Janu Jahnavi
 
MultiThreading in Python
SRINIVAS KOLAPARTHI
 
Multi Threading.docx
manohar25689
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Concurrency and Python - PyCon MY 2015
Boey Pak Cheong
 
multithreadingppt.pptx
FardeenAzhar
 
Mathemetics module
manikanta361
 

More from baabtra.com - No. 1 supplier of quality freshers (20)

PPTX
Agile methodology and scrum development
baabtra.com - No. 1 supplier of quality freshers
 
PDF
Acquiring new skills what you should know
baabtra.com - No. 1 supplier of quality freshers
 
PDF
Baabtra.com programming at school
baabtra.com - No. 1 supplier of quality freshers
 
PDF
99LMS for Enterprises - LMS that you will love
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 6 database normalisation
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 3 stored procedures
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Agile methodology and scrum development
baabtra.com - No. 1 supplier of quality freshers
 
Acquiring new skills what you should know
baabtra.com - No. 1 supplier of quality freshers
 
Baabtra.com programming at school
baabtra.com - No. 1 supplier of quality freshers
 
99LMS for Enterprises - LMS that you will love
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 6 database normalisation
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 

Recently uploaded (20)

PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PDF
Exploring-Forces 5.pdf/8th science curiosity/by sandeep swamy notes/ppt
Sandeep Swamy
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
Exploring-Forces 5.pdf/8th science curiosity/by sandeep swamy notes/ppt
Sandeep Swamy
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
Understanding operators in c language.pptx
auteharshil95
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 

Threads in python

Editor's Notes

  • #2: &lt;number&gt;
  • #3: &lt;number&gt;
  • #6: &lt;number&gt;
  • #21: &lt;number&gt;
  • #22: &lt;number&gt;