Unit 4. Chapter 2 Threads: Creating Threads in Python
Unit 4. Chapter 2 Threads: Creating Threads in Python
CHAPTER 2 THREADS
Creating Threads in Python:
Thread class of threading module is useful to create our own threads. The following are the
different ways of creating our own threads in python.
T=Thread(target=functionname,args=(agr1,arg2,..))
T thread object that represents our thread. The target represents the function on which the
thread will act. args represents the tuple of arguments which are passed to the function. Once
thread is created start() method is called to initiate it for execution. As show below.
T.start()
#create a function
def display():
print("hello")
for i in range(4):
t=Thread(target=display)
t.start()
output:
hello
hello
hello
hello
#python program to create thread and pass arguments to display function using tuple
def display(str,k):
for i in range(k):
print(str)
t=Thread(target=display,args=("hello",4))
t.start()
output:
hello
hello
hello
hello
In this method we can create a class which will be a subclass of Thread class, so that we can
inherit the functionality of the thread class. We can define a class as shown below
Class Mythread(Thread):
Mythread represents the subclass of Thread class. In this sub class override a run method of
super class to have our own code need to be executed by our own thread.
#method2
class mythread(Thread):
def run(self):
for i in range(10):
print("hello")
t1=mythread()
t1.start()
output:
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
In this method create an independent class that does not inherit from Thread class. Create a
object of independent class as shown below
class Mythread
m=Mythread(“hello”)
The next is to create a thread by creating an object to Thread class and specifying the method of
Mythread class as its target as:
T=Thread(target=m.display,args=(1,2))
#method3
class mythread:
def display(self):
print("hello")
m=mythread()
t=Thread(target=m.display)
t.start()
output:
hello
#method3
#create thread using a class and method of class act on instance varible
class mythread:
def __init__(self,s):
self.str=s
def display(self,k):
for i in range(k):
print(self.str)
m=mythread("hello")
t=Thread(target=m.display,args=(10,))
t.start()
output:
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
Method Description
t.start() Starts the thread. It must be called once per thread object. It in turn
invokes the run() method
t.is_alive() Returns true if the thread is alive in memory and false otherwise. Thread
is alive from the moment start() method until run() method terminates
t.daemon This is property that takes either true or false to set the thread as daemon
or not
Single tasking using a Thread:
A thread can execute one task at a time. Suppose there are three tasks and these are executed by a
single thread one by one then it is called as single tasking. Let a consider a program to prepare a
tea. This program contains three sub tasks which are as follows
These three sub tasks are represented through three functions task1(), task2() and task3() and we
call these three functions in maintask() function which is assigned to a thread.
Sleep(seconds) function of time module is used suspend the execution of running thread
temporarily for specified time period.
def task1():
sleep(5)
print("done")
def task2():
sleep(3)
print("done")
def task3():
sleep(3)
print("done")
def maintask():
task1()
task2()
task3()
t=Thread(target=maintask)
t.start()
output:
Example:
When we go to Movie Theater a person is there at the door to check and cut the ticket. When we
enter the movie hall there is another person who shows the chair to us. Suppose there is only one
person ( 1 thread) doing these two tasks, Then he has to first cut the ticket and then come along
with us to show the chair. Once again he has to go back to door cut the ticket and come along
with the next person to show the chair. If he does like this (1 thread) then it takes lots of time and
many people will be still waiting outside the door for their chance. To solve this problem theater
owner employ two people (2 threads) for this purpose. One will cut the ticket and the second one
will show the chair. When second one showing the chair for person enters in movie hall, the
person at door will cut the ticket of next person. Like this two person can act simultaneously and
hence there will be no wastage of time. Same situation is illustrated through a program.
#Multitasking using two threads
def movieshow(str):
for i in range(1,6):
print(str,":",i)
sleep(1)
t1=Thread(target=movieshow,args=("cut ticket",))
t2=Thread(target=movieshow,args=("show chair",))
t1.start()
t2.start()
output1:
cut ticket : 1
show chair : 1
cut ticket : 2
show chair : 2
cut ticket : 3
show chair : 3
cut ticket : 4
show chair : 4
cut ticket : 5
show chair : 5
output2:
cut ticket : 1
show chair : 1
:3
:4
:5
Please run the program several times and you can see the results are varying. Sometime the result
is not correct because before ticket cut2 show chair 2 is displayed. This is because we expected
that t1 should act first and then t2. But thread execution are controlled by processor so t2 may be
executed before t1. This is called as “RACE CONDITION”, which occurs when threads are not
acting in an expected sequences thus leading to incorrect result. Race condition can be
eliminated using synchronization.
Synchronization:
To understand the race condition let us consider one more example. Suppose two railway
reservation clerks from two different places send request for reserving a same seat at the same
time to the server. Two client request are handled by two threads, as two threads act
simultaneously on function that do the reservation, we may get a wrong result such as same seat
is reserved for two person. This is race condition this occurs because two or more thread act on
same function at the same time. To avoid race condition synchronization of thread is needed.
Mean at a time only one thread should act on a method or function.
class Railway:
def __init__(self,seats):
self.seats_av=seats
def reserve(self,w):
print("no of seats avialbel",self.seats_av)
if self.seats_av>=w:
name=current_thread().getName()
self.seats_av-=w
sleep(1)
else:
r=Railway(1)
t1=Thread(target=r.reserve,args=(1,))
t2=Thread(target=r.reserve,args=(1,))
t1.setName("First Person")
t2.setName("Second Person")
t1.start()
t2.start()
output1:
no of seats avialbel 1
no of seats avialbel 0
Output2: