0 ratings0% found this document useful (0 votes) 32 views18 pagesAdvanced Python Programming - Lesson No.003
Advanced Python Programming - Lesson No.003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
|
Threads in Python : Difference between process and thread,
benefits of threads, creating threads,
synchronization, deadlock in threads, daemon threads.
types of threads,
single tasking and multitasking, threadChapter3: Threads in Python 3110346
4
3.1 Difference between Process and Thread ——n
BZ TY 8 OF TA nnn FD
33
a4
35
36
a7
38 Daemon Threads...THREADS IN PYTHON
tak
MO
| reeds in python: ference between process and thread, types of thneads, Beefs of threads, creating
treads singe tasking and multackng thvead synchronization deadlock in threads, daemon tveads
Difference between Process and Thread
Process
1+ Processes are programs that ae dispatehed fram the ready state and scheduled for execution in the CPU. The
‘ea of process held by PC (Process Control Block. A process can generate new processes, wich are referred
to a Child Processes. The proces takes longer to complete andi is slate, which mean t des net share
memory with any other processes.
+The process mightbe in one of sixstate eh ready running waling terminated, orale
Thread
A thread i 2 section of proces, which means that 2 proces can have several threads all of which are
ontained within proces. tread ca bein one ofthre stats: runing ready, or locked
Threads require les time to terminate than processes, however une processes, threads donot isolate
‘cada [oat] [Fine
—— oo
Tweed
Fig 3aDefinition ‘A proces isa program under execution | Athread is alightweght process that inh,
Aeanactive program. managed independently by 3 she
Ccomentswitchingtime | Processes require more tine for context | Threads require less time for cont
ie seth as they are heavier. switching as they are ght than procs
Memory Sharing Processes are totally independent and | A thread may share some memory with
ont share memory peer threads.
Communication Communication between _procestes | Communication berween threads requis
requires more tne than between threads | les time than between processes
Blocked 1 proces gets blocked, remaining | if usr level thread ges locke al of
processes an continue execution peer threads also get blocked,
Resource Consumption ‘Threads generally need less resources he
—
Dependency Individual processes are independent of| Threads are parts ofa process and 30
ach other dependent
| patnandadesharing | Processes have Independent data and | A thread shares the data segment, ik
code segments. segment fle et. with ts peer threads
‘Treamment by OS [AI the diferent processes are treated | all ser level peer threads are treated a
separately bythe operating system, —_| single tas by the operating system.
“Time for reaton Processes require more time forcreation._ | Threats require ess time for craton
‘Timeforterminatin | Processes require more time for | Threads require less tme for termination
I termination
3.2 _Types of Threads
“Toereare wo typesof threads
1 Userlevelthread
2. Kerellevelthread
1 User Level thread (ULT):
User ev! treads are implemented in the use level Moray rater than through system calls. Thread switchs
es not need cll othe operating system or an interrupt tthe Kernel. The kernel is unaware ofthe were
‘thread and treats them asifthey were sngethreaded processes,‘vantages of User level threads
‘ncanbe implemented onan operating system hat dos ot alow mltithresding
‘+ simple representation sce he heed simply conta 2 programme counter, regs set anda stack pace
Easy tcontruct because no kernel volvement i reguled
Thread thing quick since n Scale ate equ
+ Teele norte cordnation between threads and he kernel
Aa singe thread creates pagel, the entre operation shale
2 Karmel evel Thread (KET):
‘The ern i aware of and mata threads Ista of having 2 trend table In each process, the Kernel
tmintans a master thread table that Keeps tack of all the threads in the sytem. In ation, the Kernel heeps 2
‘pla proces table to kee track ofthe processes. The operating stom kernel includes system cal for eating
and managing treads
Advantages Kernel Level Thread:
‘+ Because the ernel knows everything about the threads nthe system. the scheduler may decide allocate entra
‘inet processes with lage numberof treads
‘+ Bene for programmes that regula eras,
+ enecesate the use fathead conto Mock, which adds overhead
33._Benefits of Threads
‘Toreadshave following bene
1 Enhanced system throughput Whan the proces ied into mali threads, ech af which sanded 3s
2b. the umber ofjobs completed per unite ries. sae, he ystems thoughpat es,
2. Mfective Multiprocessor System Utlization: Wen you have several threads one process. You can shell
‘ule treads in multiple processors,
‘3. Faster contest switching: The tne takes osc between reads shorter than the tine takes o move
ecweenprocese. Te proces ones sich ads tothe CPU’ over.
44 Responsiveness: When a process divided into numerous treads, when one tread completes its execution
‘he proceer maybe reacted oa quickly feasible
5. Communication: Mulipethrend communion is trsghtforward snc the trends share the same adress
space but a procts we wiz just ew exclurve communiaton mechani to communkate between tr
{6 Resource sharing: Resources ike 25 ade, dt, anes can be shared throughout all threads sea process.
shoul be noted that he tack and reste anno be Share hy several threads. ach thee iss on stack
nd restr.
veea
WW Acerca ton ogamning 9S Comp) 3.4 Tieadsin yen
3.4 Creating Threads
3.4_Creating Threads
creating anew thread
‘+The thread module is used to spawn another thread provides baie synchronization data structure called
{ck object(primitive lock. simple Tock, mutual exclusion lock, mutex. and inary semaphore) To smn 3
new thread star.new thread) method used.
1+ Toproduce another thread the flowing method i avilable n.thrend module
thread start. new.threndfuncionargs[3arg))
The sartnew.thred method allows us to create new thread efficiently and fast in Linux and Windows
‘operating system. The star. new thread method cll returns immediately and it starts the child thread and
alr callthe function by passing the lit of arguments
‘+ When the function returns the thread get terminate, The ars in sytax Is noting but the tuple arguments
you want to cll any functon without pasing the argument then use the empty tuple. Awargs 2 dtonary of
ey word argument an it's optional
Example: Thread Creation
Sows: a
| tat Foe fun Open Window
[import _thread
import Time
# define a function for the thread
def print_tine( threadiane, delay):
count = 0
while count < 5:
‘time. sleep (delay)
count += 1
Print ("ta: te" & ( threadName, tine.ctine(time.time()) ))
4 create two threads as follows
try:
‘_thread.start_new_thread( print time, ("Thread-1", 2, ) )
‘Tehread. start new_thread( print_time, ("Thread-2", 4, ) )
except:
‘Print ("Error: unable to start thread")
[waiteFeb 21 23:87:42
23:87:44 2017
23:87:46 2017
23:57:46 2017
eb 21 23:57:48 2017
23:87:48 2017
23:57:50 2017
2017
2017
2017
2017
é
#
a2
S220222222
He
3
+ The tread modules etecive for oweel reading fw comparethread module with he new hesdng
rmodulethen he shred modules very inted
provides few addtional metho
(© treading actveCountd) Terese tive suber fe.
© hreadingcurentThread): returns the number fthreat objects in thecalle/s thread contra
© hreadingenumerate = Itreturealit ofall cient ace tres objets
+ The reading module has the Thread class tht implements the threading. The thread csr provides the
falowing methods
© runQ This method ity pont forties
© stat): This method sara thread by cling the un method
Jotn(time) : This method walter threads to trite,
laAlveQ: This method checks wheter trea isi engeting
etName(): This method returns the nae fathead.
stam): This method set the name fae
(resting Thread using Treading Module
Tocrete thread using heating module performs allowing steps
1 einea new subclas ofthe Freed ass
2% override the_ini_ (el Larpsmethod or adsng ational arguments
Aer tat override the rust arg) method
implement what the thread should when startet
‘Aer ereating the read sbcasceate ts instance then stare tray invoking the ar) whi il
caring meio
—eEeSGETAdvanced fython Programming (MU_BS.Co 2s Sa
et Tun(sade)
print {ianatarting = + a9l€.nanm)
Prine" (usiting "Sele ane)
ane pint tina (ehrnatane, counter, datay)
tine. sleap(aeisy)|
Deine” (ote! to" 4 (ehreadvane, ine,ctine tine. tine (0231
stare now treads
ftheseal-seaee)
theesa? seareo)
reine -\0 sting stm meme
starting Mread-t
Starting Mread-2
eiting wate theoad
o> theead-Is fue May 30 12:12:99 2017Rhread-2: Ton May 30 12:12:99 2027
exiting Tread)
[Peewad-2! fe may 20 22413.5 _ Single Tasking and Multitasking Fe
sample ofthe single tsk sytem i ven 2s
‘A singetahing system can only ran one program a tine
falows
ample
[Dopey cocina RTT 8x
Fee sony |
- ini cael
Starting a task...
done
Starting a task.
‘done
Te took 2.02 second(s) to complet
eid Cove
+ Mathreding tke multiprocessing s+ method of doing multitasking, The ken of threads Is employed i
multreading.
1+ Thecapacy ofa proceso to executemany threads concurrent isrefered tas mule
«+ eis accomplished with abs, slnge-core CPU by switching between treads often Context switching i the
tame for this When content switching occur, the sat fone thread is preserved and the sat of anathet
thread ilosded whenever an terup occurs (due 0/0 or dlberataly specifi), Contest slching occurs 50
fen that all threads appear toe executing concurrent (his istermed as mlitaskng).
+ The treading madule in Python provides very simple and ear AP fr cresting numerous threads ini
progamme
reranh IT
En’ Enredaing.threadteargoesprine square, acge"(10,))
32 5 threading. trees eaeyepristiie, tn
f,scpeing come '
Fle_tdt_ Shall Debug Options Window Help
Square: 100 =|
cube: 1000
. Done! a
Multithreaded Prorty Queue
‘The Queve model is used to create anew queue object It holds a particular number of tems. To conta
queue the following methods are used.
Ee ieee mas
1 [od __|Risnatedcneetndvarsanten fone gune |
Pm en |
redean yon Progaming MU 8 ony we Train pte
se.no | Method Description
3_[asinog__| this method return the numberof tems that are present curren nthe queue
+ [empwo
s [rio
‘wample
Import Queve
Inport ie
port threading
Fag=0
dass myThread (threading Thread}
et_Int_ (ct threaeD, name:
‘reading Thread_inlt_(sel)
setinresdD = threadlD
seliname = name
sel
defrag
print (\n Starting” + elias)
process. dataseltmame, self)
prin (\nBting*+slemame)
et proces. datathreaaName, 9)
we not Flag
quruelodacqlre)
not workqueueemy0:
Info =aget0
ueueLockrelease()
Print ("\n 9s processing 9s" (threadName no)
he:
ueuelockreease)
timesieep(t)
Ahreadlist= [Threads “Thread Threads")
‘This method returns True vale ifthe queues empty ese twill earn Fale
This method returns Truevale ithe queue fl seit wil return False |
ueuttock= threading ack)
workqueve = Queue Queus(10)
threads =[]fortName inhrendlist W crentenew trends
thread = myThread(hreaD, Name, work Queue)
vtreadstar)
hresdsappend(hread)
heat +81
queuelockacquireQ) ‘Fre queue
forwordinnameLise
work Queue putword)
quelorlease()
wile not workQuewe empty: ‘Wate for queue to empty
pase
Fags 1 Notity threads ts time to exit
fort in hrads: ‘Wale forall threads to complete
ein
print ("xing Maln Thread")
tdAdvanced yon Posing. ASC en
36 _ Thread Synchronization
Threading module hae a locking instrament hat permits wt syeronine the treads. The Lac techni
wed to make another lock, The acquire (ckng state forthe new lack question tina 9 compel heads
trun synchronously. The opina lacking parareter permits wt conrl whether the thread holds up to acquire
‘helock On the af hance that bockng quality t,he lok not acute it wl ie bck he vale O and it
‘he lacks acquired it wil pve bac he value I In he event that You st the blocking valve, hen tread gt
‘Mock and st ight fo he lock to be rleased. The rele tecngve tized to release the lok when is id
(She wymread feeding theead)
QetTainie (aeity ehrendid, name, counter):
Girwsaiig tareed. unit’ (aeid)
seie ennai = thiendiD
acting * + eet¢.name)
Ensauatoce-scquite() "Poet Lock to ayncnrontze threat
[print tine (weit one, seifvcoutes, 3)
Ehreudioct reiscce()” “free Lock to relense next thread
ae print tune (tnresctane, Galay, Sountes)
‘anes aleep (delay?
"Tee (encendtane, tine, ctine(time.tine0)))|
ng (USC Cony aa rete
‘A deadlock Is 3 scenario In which two oF more threads are stuck wating foreach ether Indefiitely. Why,
several treads require the same locks but receive them in diferent orders, deadlock ensues. A deadlock conga
«can oscar na Java mulitireaded application because the synchronced keyword forces the executing thread to ay
while waiting for the lock, or monitor, associated withthe given abject Although deadlocks rarely OCF they cus,
the aplication to stop responding when they ecu
ample:
‘port threading time
ass
lock tresding Lock)
»
occ = trending Lock)
et enreadcale)
int (Thread scgutring
slockacqute()
time stents)
Print (Thread acqutagleck")
BlockacquireQ
timeseep(3)
bees
‘rnt (Threat releasing both lock
lckselease()
slockretease()
et nrenzeateQ:
print (Thread acquiring lock")
bockacqureO
tame steep(5)
print (Thread2acqulringlock a")
slockacqule)
timesleep()barnett
beni
tn (Thread? reesing bath oc")
ockreleseD)
aleclaeeQ)
threading Treatargt = threat cle)
tetDuemen(t)
sang)
te threading Thread(arge = threads)
‘setDaemon@2)
sag
vite:
[Bryon 377 Sr
Fle Ese Shel Debug Opt
Window
Thread! acquiring lock a
‘Thread? acquiring lock b
Thread? acquiring lock a
Threadi acquiring lock B i
fess = int cas
38 _Daemon Threads
“+ Daemon Threads are those shreds that are always runing inthe backround and flr sesitanc to man or
‘on-damon treads. The Demon Threat does et prevent the main thread from quiting abd runs in the
‘bacground. This artic about threadingin Python and wel ge through daemon threads wih examples.
+ Garbage Collector i one ofthe beter instances af daemon tread sine we presume tat them threod is
‘exeating or running and fa memory problem develops the Python Vian Machin (PVM) wi instantly start
‘Garbage Coleco. The Garbage Collector wil run in he background and wash ay worthless, ater which
‘ee memory willbe roped by deface ree memory s aval the main thread wil run without sue
ss irredt
van ton Progen BS Cony on
‘Daample of Non-daemon thread
‘The examples itstrate the Now of 3 nonsdaemon tread in which we have const” 9 th#84.10 ae
function with some lns of stint run that show how the non-daemon thread is processed when The ma
then stops Following tht we generated the head of faction thread 1), which snow regarded MO aye
‘heat we now tart the head Tan we temporay pase the exeuton ofthe man head fr 8 #0 Tine
elapsed bewee th Sse Thread T cons sopra, and he man tread wl be executed a5 sen
‘where it stops working but thread Ti ti runing since tis no-daemon tread and performs her istrtin,
tl hey are completed
( (9 esanen okey“ Aran rgpoanacinpsnTiban = x}
Fle te fort Re |
¥ imgcrt nodule on ‘
Sthreading imvcrt +
,
‘ime. sleep (2)
creating a thread T
‘Thread (target=thread_1)
starting of thread T
Pestart()
main thread etop execution till 5 sec.
time. sleep (5)
print (‘main Taread
(B -Pyten 77 Sha =
Fle Est Shel Debug Options Window Help
‘thie i@ non-daemon thread
this is non-daemon thread
this is non-daemon thread
main Thread execution
>>> this is non-daemon thread
[this is non-daemon thread‘romp of Daemon thread over non-daemon rend
This san stration of how daemon treads diferrom nondaeman threads uring AMINE econ We
can see inthe preceding example how the non-daemon thread competes its execution afer the main thread
‘terminates ut this ime there isa ierece In thi example, we generated a function thread 1) and head Tote
same way a5 nthe previous example, bu ater creating thread T we use the setDaemon() metodo transform
‘on-demon nature f0 daemon nature hen we star thread T and temporary pause the execatin of the main
‘Brea. The twist that when the min thread completes Rs ection and terminates, head T also terminates
‘ect ts a daemon thread. and the work ofthe daemon thread isto support the min tread. there no min
‘tread remaining why wil the daemon tread running ther, hey also terminate while the exeeationofnstrctions
‘es orging.
[Wimpore modules
[fest threading smocs +
# creating a thread
7 Thread(tazget = thread_1)
# change 7 to daemon
TesetDaemon (25.6)
# starting of thread T
Testared)
ime. sleep (5)
pring ("shies
ouput:
Fle Eat Shek Debug Optont Window Help
[this is thread 7
this is thread 7
(this is Nain Thread
>>> this is thread 7 '
this is thread 7 ’
this is thread 7Teer dt
1 sdronet yton Programming MBS Cony 216 Threadsin Python
01 Wratistivead?
a2 Whatarethe ypes ot ead?
03 Whatarothe boots of tread 7
a4 Whatis the ditlerence between process and thread ?
25 Howto creste a tread 7 Explan wih example
a Explain thread synchronization ?
0.7 Whatisdaomon thread? Explain with example,
28 Eplain mutitreadng
2.9 Explan deasock
‘aoa