Professional Documents
Culture Documents
Btechpythonppt
Btechpythonppt
Btechpythonppt
In a Python
program, if we write a group of statements, then these statements are executed by Python
Virtual Machine (PVM) one by one.
• about the presently running thread in the program. This execution is called a thread,
because PVM uses a thread to execute these statements. This means that in every Python
program, there is always a thread running internally which is appointed by the PVM to
execute the program statements.
• Importing ‘threading’ module which is needed while dealing with threads. This module
contains a method ‘current_thread()’ that returns an object containing the information
• We can access its name using the getName() method as:
name = current_thread ().getName() # return the name of the current
# thread
• This is shown as MainThread' which is the name of an internal class in Python. We can
also access the main thread's information by calling 'main_thread()' method. Hence it is
possible to compare whether the current thread is the main thread or not using:
if threading.current_thread() == threading.main_thread():
print('The current thread is the main thread’)
This statement has displayed the output: The current thread is the main thread.
Program1:
#every Python program is run by main thread
import threading
print('Let us find the current thread')
# find the name ont thread the present thread
print('Currently running thread:',
threading.current_thread().getName())
#check if it is main thread or not
if threading.current_thread() == threading.main_thread():
print('The current thread is the main thread')
else:
print('The current thread is not main thread')
Output:
Let us find the current thread
Currently running thread: MainThread
The current thread is the main thread
Creating Threads in Python
Python provides ‘Thread’ class of threading module that is useful to create threads. To
create our own thread, we are supposed to create an object of Thread class. The following
are the different ways of creating our own threads in Python:
• Creating a thread without using a class
• Creating a thread by creating a sub class to Thread class
• Creating a thread without creating sub class to Thread class
Creating a Thread without using a Class
The purpose of a thread is to execute a group of statements like a function. So, we
can create a thread by creating an object of Thread class and pass the function name as
target for the thread as:
t = Thread (target=functionname,[args=(argl, arg2,…..)])
Here, we are creating the Thread class object 't' that represents our thread. The ‘target’
represents the function on which the thread will act. 'args' represents a tuple of
arguments which are passed to the function. Once the thread is created like this, it
should be started by calling the start() method as:
t.start()
Then the thread ‘t’ will jump into target function and executes the code in the
Program2:
# 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 for 5 times
for i in range (5):
# create the thread and specify the function as its target
t = Thread(target=display) Output:
# run the thread Hello I am running
t.start() Hello I am running
Hello I am running
Hello I am running
Hello I am running
• We can slightly improve the previous program such that we can pass
arguments or data to the display() function.
t = Thread(target-display,args=('Hello', ))
• Please observe the comma (,) after the argument 'Hello' mentioned in the
tuple. We should remember that when a single element is specified in a tuple,
a comma is needed after that element.
Program3:
# creating a thread without using a class - v2.0
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 a Thread by Creating a Sub Class to Thread Class
• Since the Thread' class is already created by the Python people in threading module, we
can make our class as a sub class to Thread class so that we can inherit the functionality of
the Thread class.
• This can be done by writing the following statement:
class MyThread (Thread):
• Here, 'MyThread' represents the sub class of Thread' class. Now, any methods of Thread
class are also available to our sub class.
• The Thread' class has the run() method which is also available to our sub class, i.e. to
'MyThread' class.
• The specialty of the run() method is that every thread will run this method when it is
started. So, by overriding the run method, we can make the threads run our own run()
method. Overriding a method – means writing our own method with the same name as the
run() method of the super class.
• The next step is to create the object of the ‘MyThread’ class which contains a copy of the
super class, i.e. the ‘Thread’ class and to join the thread join()
t1 = MyThread()
t1.join()
Program4:
# 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):
Output:
for i in range (1, 6):
1
print(i)
2
# create an instance of MyThread class
3
t1 = MyThread()
4
# start running the thread t1
5
t1.start()
# wait till the thread completes execution
t1.join()
• Sometimes, threads may want to act on the data available in the class. It
means, if the class has instance variables, the threads can act on them.
For this purpose, we have to write a constructor inside our class as:
def__init__(self,str ):
self.str= str
• This constructor accepts a string 'str' and initializes an instance variable
'self.str’ with that string. But there is a restriction here. When we write
a constructor, it will override
• the constructor of the super class, i.e. of Thread' class. So, to retain the
functionality the ‘Thread' class, we have to call its constructor from our
sub class constructor as:
def__init__(self,str):
Thread.__init__(self) # call Thread class constructor
self.str = str
Program5:
# a thread that accesses the instance variables
from threading import *
# create a class as sub class to Thread class
class MyThread (Thread):
# constructor that calls Thread class constructor
def__init__(self, str):
Thread.__init__(self)
self.str = str Output:
# override the run() method of Thread class Hello
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 execution
t1.join()
Creating a Thread without Creating Sub Class to Thread Class
• We can create an independent class say 'MyThread' that does not inherit from
‘Thread’ class.
Then we can create an object 'obj' to 'MyThread' class as:
Obj=MyThread('Hello’)
• The next step is to create a thread by creating an object to ‘Thread’ class and
specifying the method of the 'MyThread' class as its target as:
• Here, 'tl' is our thread which is created as an object of Thread' class. 'target'
represents the display() method of 'MyThread' object 'obj'. 'args' represents a tuple
of values passed to the method. When the thread 't1' is started, it will execute the
display() method of 'MyThread' class. This is shown in Program 6.
Program6:
# a thread that accesses the instance variables
from threading import *
# create a class as sub class to Thread class
class MyThread (Thread):
# constructor that calls Thread class constructor Output:
def__init__(self, str): Hello
Thread.__init__(self) The args are: 1, 2
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 execution
t1.join()
Single Tasking using a Thread
• A thread can be employed to execute one task at a time. Suppose there are 3 tasks and
these are executed by a thread one by one, then it is called single tasking.
• Let's plan a program for preparation of tea in three steps as:
1. Boil milk and tea powder for 5 minutes. This is task1.
2. Add sugar and boil for 3 minutes. This is task2.
3. Filter it and serve. This is task3.
• These 3 tasks can be represented as separate methods: task1(), task2() and
task3().These three methods should be called from a main method of the class as:
def prepareTea (self): # this is main method
self.task1()
self. task2()
self.task3()
• Here, the main method is prepareTea() from where the other methods are called. When
we create the thread, we have to make this main method as target for the thread.
• Then the thread will jump into this main method and execute all the other 3 methods
one by one. This is shown in Program 7
In this program, we are showing the time with the help of sleep() function of time
module as:
sleep(seconds)
• This function temporarily suspends execution of the running thread for the
specified time given in seconds.
• The time taken by a thread in performing some activity can be shown as time
delay using the sleep() function.
• Please observe that in task1() method, while boiling milk and tea powder for 5
minutes, we used sleep (5). Thus, the time is actually delayed to represent the 5
minutes boiling activity. for 5 seconds
Program7:
#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 minutes...', end='')
sleep (5)
print('Done')
def task2 (self):
print('Add sugar and boil for 3 minutes...', end='')
sleep(3)
print('Done')
def task3(self):
print('Filter it 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()
Output:
Boil milk and tea powder for 5 minutes...Done
Add sugar and boil for 3 minutes...Done
Filter it and serve...Done
Multitasking using Multiple Threads
• In multitasking, several tasks are executed at a time. For this purpose, we need more
than one thread. For example, to perform 2 tasks, we can take 2 threads and attach them
to the 2 tasks. Then those tasks are simultaneously executed by the two threads.
• Using more than one thread is called 'multi threading' and multi threading is used in
multitasking.
• When we go to a movie theatre, generally a person is there at the door-checking and
cutting the tickets. When we enter the hall, there is another person who shows the chairs
to us. Suppose there is only one person (1 thread) doing these two tasks. He has to first
cut the ticket and then come along with the first person to show the chair. Then he goes
back to the door to cut the second ticket and then again walk with the second person to
show the chair. Like this, if he does the things one by one, it takes a lot of time, and even
though the show is over, there will be still people left outside the door waiting to enter
the hall! This is pretty well known to the theatre management. So what they do?
• They employ two persons (2 threads) for this purpose. The first person will cut the ticket,
and the second one will show the chair. When the second person is showing the chair, the
first person cuts the second ticket. Like this, both the persons can act simultaneously and
hence there will be no wastage of time. This is shown in Program 8.
Program8:
# multitasking using two threads
from threading import *
from time import *
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(0.1)
# create two instances 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) Output:
# run the threads Cut ticket:1
t1.start() show chair:1
t2.start() Cut ticket:2
show chair:2
Cut ticket:3
show chair:3
Cut ticket:4
show chair:4
Cut ticket:5
show chair:5
• Let's take the case of railway reservation. Every day several people want reservation of a
berth for them.
• Let's think that only one berth is available in a train, and two passengers(threads) are
asking for that berth. Let's assume that in reservation counter no.1, the clerk has sent a
request to the server to allot that berth to his passenger. In counter no.2,the second clerk
has also sent a request to the server to allot that berth to his passenger. It means two
passengers are competing for the same berth. Let's see to whom that berth is allotted.1
berths allotted for Second Person.
• The threads t1' and '12' are running on the reserve() method of Railway class.
• Since we have taken the available number of berths as 1, when thread 't1' enters the
reserve() method, it sees available number of berths as 1 and hence, it allots it to First
Person and displays:
1 berths allotted for First Person
• Then it will sleep for 1.5 seconds. In this time, the ticket will be printed on the printer.
When the first thread is sleeping, thread t2' also enters the reserve() method, and it also
sees that there is 1 berth remaining. The reason for this is that the available number of
berths is not yet updated by the first thread. So the second thread also sees 1 berth as
available, and it allots the same berth to the Second Person.
• Then the thread 't2' will also go into sleep state. Thread 't1' wakes up first, and then
it updates the available number of berths as:
self.available-=wanted
• Now available number of berths will become 0. But by this time, the second thread
has already allotted the same berth to the Second Person also. Since both the threads
are acting on the same object simultaneously, the result is unreliable. What is the
solution for this problem? You may think to update the number of berths first and
then let the thread go for sleep. So, you want to write the following sequence of
statements:
self.available-= wanted
sleep (1.5)
• If you write in this way also, there is no guarantee that we will get correct output. It
may display something like this:
Available no. of berths=1
1 berths allotted for First Person
Available no. of berths=1
Sorry, no berths to allot
Program9:
# multitasking using two threads
from threading import *
from time import *
class Railway:
# constructor 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 berths
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 berth is allotted for the person
print('%d berths allotted for %s' %(wanted, name))
#make time delay so that the ticket is printed
sleep (1.5)
#decrease the no. of available berths
self.available-= wanted
else:
#if available < wanted, then say sorry
print('Sorry, no berths to allot')
# create instance to Railway class
# specify only one berth is available Output:
obj = Railway (1) Available no. of berths= 1
# create two threads and specify 1 berth is needed 1 berths allotted for First Person
t1 = Thread (target=obj.reserve, args=(1,)) Available no. of berths= 1
t2 = Thread (target=obj.reserve, args=(1,)) 1 berths allotted for Second Person
# give names to the threads
t1.setName('First Person')
t2.setName('Second Person')
#run the threads
t1.start()
t2.start()
Thread Synchronization
When the thread is already acting on an object, preventing any other thread from acting
on the same object is called 'thread synchronization' or 'thread safe’.The object on which
the threads are synchronized is called ‘synchronized object’ or 'mutex'(mutually exclusive
threads are lock). Thread synchronization is
done using the following techniques:
Using locks
Using semaphores
Locks
Locks can be used to lock the object on which the thread is acting. When a thread enters
the object, it locks the object and after the execution is completed, it will unlock the
object and comes out of it. A thread also locks the object after entering it. Then the next
thread cannot enter it till the first thread comes out. This means the object is locked
mutually on threads. So, this locked object is called 'mutex'(mutually exclusive lock).
We can create a lock by creating an object of Lock class as:
1 = Lock()
To lock the current object, we should use acquire() method as:
1.acquire()
t2
t1
fig:Thread Synchronization
cancelticket