0% found this document useful (0 votes)
197 views

Unit 4. Chapter 2 Threads: Creating Threads in Python

The document discusses different ways to create threads in Python. It describes 3 main methods: 1) Creating a thread object using the Thread class, 2) Creating a subclass of Thread, and 3) Creating a thread without subclassing Thread by passing a target function. It also covers thread synchronization to avoid race conditions when multiple threads access shared resources simultaneously.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
197 views

Unit 4. Chapter 2 Threads: Creating Threads in Python

The document discusses different ways to create threads in Python. It describes 3 main methods: 1) Creating a thread object using the Thread class, 2) Creating a subclass of Thread, and 3) Creating a thread without subclassing Thread by passing a target function. It also covers thread synchronization to avoid race conditions when multiple threads access shared resources simultaneously.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

UNIT 4.

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.

1. Creating a thread using thread class object

In this method we create a object of thread class using following syntax

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()

#python program to create a thread using a thread class

from threading import *

#create a function

def display():

print("hello")

#create a thread using thread class

for i in range(4):

t=Thread(target=display)

#run the thread

t.start()

output:

hello

hello
hello

hello

#python program to create thread and pass arguments to display function using tuple

from threading import *

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

2. Creating a Thread by creating a sub class to Thread class

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

#create a thread by creating a subclass

from threading import *

class mythread(Thread):

#override run method

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

3. Creating a Thread without creating sub class of Thread class

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

#create a thread without using sub class


from threading import *

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

from threading import *

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

All the above programs I explained already through video.

Thread class methods


Predefined functions of Thread class we often use in program are explained below. In all method
t represents Thread class object

Method Description
t.start() Starts the thread. It must be called once per thread object. It in turn
invokes the run() method

t.join([timeout]) Waits until the thread terminates or a timeout occurs. Timeout is a


floating point number specifying a timeout for the operation in seconds

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.setName(name) Gives a name to the thread

t.getName() Returns name of the thread

t.name This is a property that represents the thread’s name

t.setDaemon(flag) Makes a thread a daemon thread if the flag is True

t.isDaemon() Returns true if the thread is a daemon thread, otherwise false

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

1. Boil milk and tea powder for 5 minutes


2. Add sugar and boil for 3 minutes
3. Filter it and serve

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.

#python program to show single tasking using thread

from threading import *

from time import *

def task1():

print("boil milk and tea powder for 5 minute",end='')

sleep(5)

print("done")

def task2():

print("sugar and boil for 3 minutes", end='')

sleep(3)

print("done")

def task3():

print("filter it and serve", end='')

sleep(3)
print("done")

def maintask():

task1()

task2()

task3()

t=Thread(target=maintask)

t.start()

output:

boil milk and tea powder for 5 minutedone

sugar and boil for 3 minutesdone

filter it and servedone

Multitasking using Multiple Threads


In multitasking several tasks are executed at a time. For these purpose we need to create more
than one thread. To perform two tasks we can create two threads and assign them to the 2 tasks.
Then those tasks are executed simultaneously by the two threads. Using more than one thread is
called multi threading and is used in multitasking.

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

from threading import *

from time import *

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

cut ticketshow chair : 2 : 2

cut ticketshow chair : 3

:3

cut ticketshow chair : 4

:4

show chaircut ticket : 5

: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.

#pyhton program to illustrate race condition through seat reservation

from threading import *

from time import *

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()

print("seat is alloted for",name)

self.seats_av-=w

sleep(1)

else:

print("Sorry no seats are avialble")

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

seat is alloted for First Person

no of seats avialbel 0

Sorry no seats are avialble

Output2:

no of seats avialbelno of seats avialbel 1

seat is alloted for Second Person

Sorry no seats are avialble

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy