08_POSIX Threads Programming Class
-
Upload
augusto-giles -
Category
Documents
-
view
230 -
download
0
Transcript of 08_POSIX Threads Programming Class
-
8/6/2019 08_POSIX Threads Programming Class
1/21
4/25/11
1
POSIXThreadsProgramming
AtutorialbyBlaiseBarney
LivermoreCompu>ng(LawrenceLivermoreNa>onalLabs)
hDps://compu>ng.llnl.gov/tutorials/pthreads/
1
Thread
Tothesowaredeveloper,theconceptof a"procedure"thatrunsindependently fromitsmain
programmaybestdescribeathread.
Consideramainprogramthatcontainsanumberofprocedures.Alloftheseprocedurescanbe
scheduledtorunsimultaneouslyand/or
independentlybytheopera>ngsystem.Thisisa
"mul>-threaded"program.
Athreadcanbedefinedasanindependentstreamofinstruc>onsthatcanbescheduledtorunassuchby
theopera>ngsystem.2
Aprocessiscreatedbytheopera>ngsystem,andrequiresafairamountof"overhead".Processescontaininforma>onaboutprogramresourcesandprogramexecu>onstate,including: ProcessI,processgroupI,userI,andgroupI EnvironmentWorkingdirectory. Programinstruc>ons Registers StackHeap Filedescriptors Signalac>ons Sharedlibraries Inter-processcommunica>ontools(suchasmessagequeues,pipes,semaphores,orsharedmemory).
3
Threadsuseandexistwithinprocessresources,yetareabletobescheduledbytheopera>ng
systemandrunasindependenten>>eslargely
becausetheyduplicateonlythebareessen>al
resourcesthatenablethemtoexistasexecutable
code.
Thisindependentflowofcontrolisaccomplishedbecauseathreadmaintainsitsown:
StackpointerRegistersSchedulingproper>es(suchaspolicyorpriority)SetofpendingandblockedsignalsThreadspecificdata.
4
-
8/6/2019 08_POSIX Threads Programming Class
2/21
4/25/11
2
5
Insummary,intheUNIXenvironmentathread:ExistswithinaprocessandusestheprocessresourcesHasitsownindependentflowofcontrolaslongasitsparentprocessexistsandtheOSsupportsit
uplicatesonlytheessen>alresourcesitneedstobeindependentlyschedulable
Maysharetheprocessresourceswithotherthreadsthatactequallyindependently(anddependently)
iesiftheparentprocessdies-orsomethingsimilar Is"lightweight"becausemostoftheoverheadhasalreadybeenaccomplishedthroughthecrea>onofits
process.
6
Because threads within the same process shareresources:
Changes made by one thread to shared systemresources (such as closing a file) will be seen by all
other threads.
Two pointers having the same value point to thesame data.
Reading and writing to the same memory locationsis possible, and therefore requires explicit
synchronization by the programmer.7
PthreadsOverview PthreadsaredefinedasasetofClanguageprogrammingtypesandprocedurecalls,implementedwithapthread.hheader/includefileandathreadlibrary-thoughthethislibrarymaybepartofanotherlibrary,suchaslibc.
Whencomparedtothecostofcrea>ngandmanagingaprocess,athreadcanbecreatedwithmuchlessopera>ngsystemoverhead.Managingthreadsrequiresfewersystemresourcesthanmanagingprocesses.
8
-
8/6/2019 08_POSIX Threads Programming Class
3/21
4/25/11
3
Thefollowingtablecompares>mingresultsforthefork()subrou>neandthe
pthreads_create()subrou>ne.Timingsreflect
50,000process/threadcrea>ons,were
performedwiththe>meu>lity,andunitsare
inseconds,noop>miza>onflags.
9
Tempoparaacriaode50.000
processosouthreads(emseg)
10
All threads within a process share the sameaddress space. Inter-thread communication is
more efficient and in many cases, easier to use
than inter-process communication.
In particular, if an application is using MPI foron-node communications, there is a potential
that performance could be greatly improved by
using Pthreads for on-node data transfer
instead.
11
SMP-SymmetricMul+processing,acomputerarchitecturethatprovidesfastperformancebymakingmul>pleCPUsavailabletocompleteindividualprocessessimultaneously(mul>processing).Unlikeasymmetricalprocessing,anyidleprocessorcanbeassignedanytask,andaddi>onalCPUscanbeaddedtoimproveperformanceandhandleincreased
loads.Avarietyofspecializedopera>ngsystemsandhardwarearrangementsareavailabletosupportSMP.Specificapplica>onscanbenefitfromSMPifthecodeallowsmul>threading.(www.webopedia.com)
12
-
8/6/2019 08_POSIX Threads Programming Class
4/21
4/25/11
4
MPI-TheMessagePassingInterface(MPI)isa
libraryspecifica>onformessage-passing.Itis
astandardAPI(Applica>onProgramming
Interface)thatcanbeusedtocreateparallel
applica>ons.(www.webopedia.com)
13
Threaded applications offerpotential performancegains and practical advantages over non-threadedapplications in several other ways:
Overlapping CPU work with I/O: For example, aprogram may have sections where it is performing along I/O operation. While one thread is waiting for anI/O system call to complete, CPU intensive work canbe performed by other threads.
Priority/real-time scheduling: tasks which are moreimportant can be scheduled to supersede or interruptlower priority tasks.
Asynchronous event handling: tasks which serviceevents of indeterminate frequency and duration can beinterleaved. For example, a web server can bothtransfer data from previous requests and manage thearrival of new requests.
14
MPI libraries usually implement on-node taskcommunication via shared memory, which
involves at least one memory copy operation
(process to process).
For Pthreads there is no intermediate memory copyrequired because threads share the same address
space within a single process. There is no data
transfer, per se. It becomes more of a cache-to-
CPU ormemory-to-CPUbandwidth (worst case)situation. These speeds are much higher.
Some local comparisons are shown below:
15 16
-
8/6/2019 08_POSIX Threads Programming Class
5/21
4/25/11
5
DesigningThreadedPrograms Onmul>-cpumachines,pthreadsaresuitedforparallelprogramming,andwhateverappliestoparallelprogrammingingeneral,appliestoparallelpthreadsprograms.
TotakeadvantageofPthreads,aprogrammustbeorganizedintodiscrete,independenttaskswhichcanexecuteconcurrently.For
example,ifrou>ne1androu>ne2canbeinterchanged,interleavedand/oroverlappedinreal>me,theyarecandidatesforthreading.
17
interchanged
interleaved
overlaped
18
Pthreadscanalsobeusedforserialapplica>ons,toemulateparallelexecu>on.A
perfectexampleisthetypicalwebbrowser,
whichformostpeople,runsonasinglecpu
desktop/laptopmachine.Manythingscan
"appear"tobehappeningatthesame>me.
19
Commonmodelsforthreadedprograms:Manager/worker: asinglethread,themanagerassignsworktootherthreads,theworkers.Typically,themanagerhandlesallinputandparcelsoutworktotheothertasks.
Pipeline:ataskisbrokenintoaseriesofsubopera>ons,eachofwhichishandledinseries,butconcurrently,byadifferentthread .Anautomobileassemblylinebestdescribesthismodel.
Peer:similartothemanager/workermodel,butaerthemainthreadcreatesotherthreads,itpar>cipatesinthework.
20
-
8/6/2019 08_POSIX Threads Programming Class
6/21
4/25/11
6
SharedMemoryModel:
Allthreadshaveaccesstothesameglobal,sharedmemory
Threadsalsohavetheirownprivatedata Programmersareresponsibleforsynchronizingaccess,protec>ngglobally
shareddata.
21 22
Thread-safeness :anapplica>on'sabilitytoexecutemul>plethreadssimultaneouslywithout"clobbering"shareddataorcrea>ng"race"condi>ons.
Forexample,supposeanapplica>oncreatesseveralthreads,eachofwhichmakesacalltothesamelibraryrou>ne:
Thislibraryrou>neaccesses/modifiesaglobalstructureorloca>oninmemory.
Aseachthreadcallsthisrou>neitispossiblethattheymaytrytomodifythisglobalstructure/memoryloca>onatthesame>me.
Iftherou>nedoesnotemploysomesortofsynchroniza>onconstructstopreventdatacorrup>on,thenitisnotthread-safe.
sobrepor
23 24
-
8/6/2019 08_POSIX Threads Programming Class
7/21
4/25/11
7
Theimplica>ontousersofexternallibraryrou>nesisthatifyouaren't100%certaintherou>neisthread-safe,thenyoutakeyourchanceswithproblemsthatcouldarise.
Recommenda>on:Becarefulifyourapplica>onuseslibrariesorotherobjectsthatdon'texplicitlyguaranteethread-safeness.Whenindoubt,assumethattheyarenot
thread-safeun>lprovenotherwise.Thiscanbedoneby"serializing"thecallstotheuncertainrou>ne,etc.
25
ThePthreadsAPI
ThePthreadsAPIisdefinedintheANSI/IEEE
POSIX1003.1-1995standard.
Thesubrou>neswhichcomprisethePthreads
APIcanbeinformallygroupedintothree
majorclasses:
1. Threadmanagement2. Mutexes3. Condi>onVariables
26
1.Threadmanagement:Thefirstclassof
func>onsworkdirectlyonthreads-
crea>ng,detaching,joining,etc.They
includefunc>onstoset/querythread
aDributes(joinable,schedulingetc.)
27
2.Mutexes:Thesecondclassoffunc>ons
dealwithsynchroniza>on,calleda"mutex",
whichisanabbrevia>onfor"mutual
exclusion".Mutexfunc>onsprovidefor
crea>ng,destroying,lockingandunlocking
mutexes.Theyarealsosupplementedby
mutexaDributefunc>onsthatsetormodifyaDributesassociatedwithmutexes.
28
-
8/6/2019 08_POSIX Threads Programming Class
8/21
4/25/11
8
3.Condi@onvariables:Thethirdclassof
func>onsaddresscommunica>onsbetween
threadsthatshareamutex.Theyarebased
uponprogrammerspecifiedcondi>ons.This
classincludesfunc>onstocreate,destroy,
waitandsignalbaseduponspecifiedvariable
values.Func>onstoset/querycondi>on
variableaDributesarealsoincluded.
29
Rou;nePrefix Func;onalGroup
pthread_Threadsthemselvesand
miscellaneoussubrou>nes
pthread_aAr_ ThreadaDributesobjects
pthread_mutex_ Mutexes
pthread_mutexaAr_ MutexaDributesobjects.
pthread_cond_ Condi>onvariables
pthread_condaAr_ Condi>onaDributesobjects
30
ThePthreadsAPIcontainsaround100subrou>nes.Thistutorialwillfocusona
subsetofthese-specifically,thosewhichare
mostlikelytobeimmediatelyusefultothe
beginningPthreadsprogrammer.
Forportability,thepthread.hheaderfileshouldbeincludedineachsourcefileusingthePthreadslibrary.
31
1.ThreadManagement
32
-
8/6/2019 08_POSIX Threads Programming Class
9/21
4/25/11
9
ThreadManagement
pthread_create(thread,attr,start_routine,arg)
pthread_exit (status)
pthread_attr_init (attr)pthread_attr_destroy (attr)
33
Crea>ngThreads: Ini>ally,yourmain()programcomprisesasingle,defaultthread.Allotherthreadsmust
beexplicitlycreatedbytheprogrammer.
pthread_create createsanewthreadandmakesitexecutable.Thisrou>necanbe
calledanynumberof>mesfromanywhere
withinyourcode.
34
pthread_create
(thread,attr,start_routine,arg)
pthread_createarguments: thread:Anopaque,uniqueiden>fierforthenewthreadreturnedbythesubrou>ne.
aDr:AnopaqueaDributeobjectthatmaybeusedtosetthreadaDributes.YoucanspecifyathreadaDributes
object,orNULLforthedefaultvalues.
start_rou>ne:theCrou>nethatthethreadwillexecuteonceitiscreated.
arg:Asingleargumentthatmaybepassedtostart_rou>ne.Itmustbepassedbyreferenceasapointer
castoftypevoid.NULLmaybeusedifnoargumentisto
bepassed.35
Themaximumnumberofthreadsthatmaybecreatedbyaprocessisimplementa>ondependent.
Oncecreated,threadsarepeers,andmaycreateotherthreads.Thereisnoimpliedhierarchy ordependencybetweenthreads.
Ques;on:Aerathreadhasbeencreated,howdoyouknowwhenitwillbe
scheduledtorunbytheopera>ngsystem?
NSWER:UnlessyouareusingthePthreadsschedulingmechanism, itisupto
theimplementa>onand/oropera>ngsystemtodecidewhereandwhen
threadswillexecute .Robustprogramsshouldnotdependuponthreads
execu>nginaspecificorder.
36
-
8/6/2019 08_POSIX Threads Programming Class
10/21
4/25/11
10
ThreadADributes: Bydefault,athreadiscreatedwithcertainaDributes.SomeoftheseaDributescanbe
changedbytheprogrammerviathethread
aDributeobject.
pthread_attr_init andpthread_attr_destroy areusedto
ini>alize/destroythethreadaDributeobject.
Otherrou>nesarethenusedtoquery/setspecificaDributesinthethreadaDributeobject. SomeoftheseaDributeswillbediscussedlater.
37
Termina>ngThreads: ThereareseveralwaysinwhichaPthreadmaybeterminated:
Thethreadreturnsfromitsstar>ngrou>ne(themainrou>nefortheini>althread).
Thethreadmakesacalltothepthread_exitsubrou>ne(coveredbelow).
Thethreadiscanceledbyanotherthreadviathepthread_cancel rou>ne(notcoveredhere).
Theen>reprocessisterminatedduetoacalltoeithertheexecorexit subrou>nes.
38
pthread_exitisusedtoexplicitlyexitathread.Typically,thepthread_exit()rou>neiscalledaerathreadhascompleteditsworkandisnolongerrequiredtoexist.
Ifmain()finishesbeforethethreadsithascreated,andexitswithpthread_exit(),theotherthreadswillcon>nuetoexecute.Otherwise,theywillbeautoma>callyterminatedwhenmain()finishes.
Theprogrammermayop>onallyspecifyatermina>onstatus,whichisstoredasavoidpointerforanythreadthatmayjointhecallingthread.
Cleanup:thepthread_exit()rou>nedoesnotclosefiles;anyfilesopenedinsidethethreadwillremainopenaerthethreadisterminated.
39
iscussion:Insubrou>nesthatexecuteto
comple>onnormally,youcanoendispense
withcallingpthread_exit()-unless,ofcourse,
youwanttopassareturncodeback.However,
thereisadefiniteproblemifmain()completes
beforethethreadsitspawned.
Ifyoudon'tcallpthread_exit()explicitly,when
main()completes,theprocess(andallthreads)willbeterminated.Bycalling
pthread_exit()inmain(),theprocessandallof
itsthreadswillbekeptaliveeventhoughallof
thecodeinmain()hasbeenexecuted.40
-
8/6/2019 08_POSIX Threads Programming Class
11/21
4/25/11
11
A"helloworld"Pthreadsprogramemonstratesthreadcrea>onandtermina>on
#include
#include #include
#define NUM_THREADS 5void *PrintHello(void *threadid) {
long tid;
tid = (long)threadid;printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);}
int main(int argc, char *argv[]) {pthread_t threads[NUM_THREADS];
int rc; long t;for(t=0;tngthread1
HelloWorld!It'sme,thread#0!
Inmain:crea>ngthread2
HelloWorld!It'sme,thread#1!
HelloWorld!It'sme,thread#2!
Inmain:crea>ngthread3
Inmain:crea>ngthread4
HelloWorld!It'sme,thread#3!
HelloWorld!It'sme,thread#4!
42
PassingrgumentstoThreads
Thepthread_create()rou>nepermitstheprogrammertopassoneargumenttothe
threadstartrou>ne.Forcaseswheremul>ple
argumentsmustbepassed,thislimita>onis
easilyovercomebycrea>ngastructurewhich
containsallofthearguments,andthen
passingapointertothatstructureinthepthread_create()rou>ne.
Allargumentsmustbepassedbyreferenceandcastto(void*).
43
ThreadrgumentPassing(Incorrect)
Thisexampleperformsargumentpassingincorrectly.Itpassestheaddressofvariablet,whichissharedmemoryspaceand
visibletoallthreads.Astheloopiterates,thevalueofthis
memoryloca;onchanges,possiblybeforethecreated
threadscanaccessit.
int rc; long t;
for(t=0; t
-
8/6/2019 08_POSIX Threads Programming Class
12/21
4/25/11
12
ThreadManagement
Crea>ngTermina>ng Joining etaching Managingstack
45
JoiningandDetachingThreads
pthread_join (threadid,status)pthread_detach
(threadid,status)
pthread_attr_setdetachstate(attr,detachstate)
pthread_attr_getdetachstate(attr,detachstate)
"Joining"isonewaytoaccomplishsynchroniza>onbetweenthreads.For
example:46
47
Thepthread_join() subrou>neblocksthecallingthreadun>lthespecifiedthreadidthreadterminates.
Theprogrammerisabletoobtainthetargetthread'stermina>onreturnstatusifitwasspecifiedinthetargetthread'scalltopthread_exit().
Ajoiningthreadcanmatchonepthread_join()call.ItisalogicalerrortoaDemptmul>plejoinsonthesamethread.
Twoothersynchroniza>onmethods,mutexesandcondi>onvariables,willbediscussedlater.
48
-
8/6/2019 08_POSIX Threads Programming Class
13/21
4/25/11
13
Whenathreadiscreated,oneofitsaDributesdefineswhetheritisjoinableordetached.
Onlythreadsthatarecreatedasjoinablecan
bejoined.Ifathreadiscreatedasdetached,it
canneverbejoined.
ThefinaldraofthePOSIXstandardspecifiesthatthreadsshouldbecreatedasjoinable.
However,notallimplementa>onsmayfollowthis.
49
Toexplicitlycreateathreadasjoinableordetached,theaDrargumentinthe
pthread_create()rou>neisused.Thetypical4
stepprocessis:
eclareapthreadaDributevariableofthepthread_aDr_tdatatype
Ini>alizetheaDributevariablewithpthread_aDr_init()
SettheaDributedetachedstatuswithpthread_aDr_setdetachstate()
Whendone,freelibraryresourcesusedbytheaDributewithpthread_aDr_destroy()
50
Thepthread_detach()rou>necanbeusedtoexplicitlydetachathreadeventhoughit
wascreatedasjoinable.
Thereisnoconverserou>ne.
51
Ifathreadrequiresjoining,considerexplicitlycrea>ngitasjoinable.Thisprovidesportability
asnotallimplementa>onsmaycreatethreads
asjoinablebydefault.
Ifyouknowinadvancethatathreadwillneverneedtojoinwithanotherthread,considercrea>ngitinadetachedstate.Some
systemresourcesmaybeabletobefreed.
hDps://compu>ng.llnl.gov/tutorials/pthreads/samples/join1.c
52
-
8/6/2019 08_POSIX Threads Programming Class
14/21
4/25/11
14
ThreadManagement
Crea>ngTermina>ngJoiningetaching Managingstack
53
StackManagement
pthread_attr_getstacksize (attr, stacksize) pthread_attr_setstacksize (attr, stacksize) pthread_attr_getstackaddr (attr, stackaddr) pthread_attr_setstackaddr (attr, stackaddr) Exceedingthedefaultstacklimitisoenveryeasytodo,withtheusualresults:programtermina>onand/
orcorrupteddata.
Safeandportableprogramsdonotdependuponthedefaultstacklimit,butinstead,explicitlyallocateenoughstackforeachthreadbyusingthe
pthread_aDr_setstacksizerou>ne.
54
2.Mutexes
55
MutexVariables Mutexisanabbrevia>onfor"mutualexclusion".Mutexvariablesareoneoftheprimarymeansofimplemen>ngthreadsynchroniza>onandforprotec>ngshareddatawhenmul>plewritesoccur.
Amutexvariableactslikea"lock"protec>ngaccesstoashareddataresource.ThebasicconceptofamutexasusedinPthreadsisthatonlyonethreadcanlock(orown)amutexvariableatanygiven>me.Thus,evenifseveralthreadstrytolockamutexonlyonethreadwill
besuccessful.Nootherthreadcanownthatmutexun>ltheowningthreadunlocksthatmutex.Threadsmust"taketurns"accessingprotecteddata.
Mutexescanbeusedtoprevent"race"condi>ons.Anexampleofaracecondi>oninvolvingabanktransac>onisshownbelow:
56
-
8/6/2019 08_POSIX Threads Programming Class
15/21
4/25/11
15
Intheexamplebelow,amutexshouldbeusedtolockthe"Balance"whileathreadisusing
thisshareddataresource.
Veryoentheac>onperformedbyathreadowningamutexistheupda>ngofglobal
variables.Thisisasafewaytoensurethat
whenseveralthreadsupdatethesame
variable,thefinalvalueisthesameaswhatit
wouldbeifonlyonethreadperformedtheupdate.Thevariablesbeingupdatedbelongto
a"cri>calsec>on".
57
Thread1 Thread2 Balance
Readbalance:
$1000$1000
Readbalance:
$1000$1000
eposit$200 $1000
eposit$200 $1000
Updatebalance$1000+$200
$1200
Updatebalance
$1000+$200$1200
58
Atypicalsequenceintheuseofamutexisasfollows:
Createandini>alizeamutexvariableSeveralthreadsaDempttolockthemutexOnlyonesucceedsandthatthreadownsthemutex
Theownerthreadperformssomesetofac>onsTheownerunlocksthemutexAnotherthreadacquiresthemutexandrepeatstheprocess
Finallythemutexisdestroyed59
Whenseveralthreadscompeteforamutex,thelosersblockatthatcall-anunblockingcall
isavailablewith"trylock"insteadofthe"lock"
call.
Whenprotec>ngshareddata,itistheprogrammer'sresponsibilitytomakesure
everythreadthatneedstouseamutexdoes
so.Forexample,if4threadsareupda>ngthe
samedata,butonlyoneusesamutex,the
datacans>llbecorrupted.
60
-
8/6/2019 08_POSIX Threads Programming Class
16/21
4/25/11
16
Crea;ngandDestroyingMutexes
pthread_mutex_init(mutex,aAr)pthread_mutex_destroy(mutex)
pthread_mutexaAr_init(aAr) pthread_mutexaAr_destroy(aAr)
61
Mutexvariablesmustbedeclaredwithtypepthread_mutex_t,andmustbeini>alized
beforetheycanbeused.Therearetwoways
toini>alizeamutexvariable:
Sta>cally,whenitisdeclared.Forexample:pthread_mutex_tmymutex=
PTHREA_MUTEX_INITIALIZER;
ynamically,withthepthread_mutex_init()rou>ne.Thismethodpermitssengmutexobject
aDributes,a5r.
62
Thea5robjectisusedtoestablishproper>esforthemutexobject,andmustbeoftype
pthread_mutexaDr_tifused(maybespecified
asNULLtoacceptdefaults).ThePthreads
standarddefinesthreeop>onalmutex
aDributes:
Protocol:Specifiestheprotocolusedtopreventpriorityinversionsforamutex.
Prioceiling:Specifiesthepriorityceilingofamutex.
Process-shared:Specifiestheprocesssharingofamutex.
63
Notethatnotallimplementa>onsmayprovidethethreeop>onalmutexaDributes.
Thepthread_mutexaDr_init()andpthread_mutexaDr_destroy()rou>nesare
usedtocreateanddestroymutexaDribute
objectsrespec>vely.
pthread_mutex_destroy()shouldbeusedtofreeamutexobjectwhichisnolonger
needed.
64
-
8/6/2019 08_POSIX Threads Programming Class
17/21
4/25/11
17
LockingandUnlockingMutexes
pthread_mutex_lock(mutex)pthread_mutex_trylock(mutex)
pthread_mutex_unlock(mutex) Thepthread_mutex_lock()rou>neisusedbyathreadtoacquirealockonthespecified
mutexvariable.Ifthemutexisalreadylockedbyanotherthread,thiscallwillblockthecallingthreadun>lthemutexisunlocked.
65
pthread_mutex_trylock()willaDempttolockamutex.However,ifthemutexisalready
locked,therou+newillreturnimmediately
witha"busy"errorcode.Thisrou>nemaybe
usefulinpreven+ngdeadlockcondi+ons,asin
apriority-inversionsitua>on.
66
pthread_mutex_unlock()willunlockamutexifcalledbytheowningthread.Callingthis
rou>neisrequiredaerathreadhas
completeditsuseofprotecteddataifother
threadsaretoacquirethemutexfortheir
workwiththeprotecteddata.Anerrorwillbe
returnedif:IfthemutexwasalreadyunlockedIfthemutexisownedbyanotherthread
67
Thereisnothing"magical"aboutmutexes...infacttheyareakintoa"gentlemen'sagreement"betweenpar>cipa>ngthreads.Itisuptothecodewritertoinsurethatthenecessarythreadsallmakethemutexlockandunlockcallscorrectly.Thefollowingscenariodemonstratesalogicalerror:
Thread1Thread2 Thread3
Lock Lock
A=2 A=A+1 A=A*B
Unlock Unlock
68
-
8/6/2019 08_POSIX Threads Programming Class
18/21
4/25/11
18
Ques>on:Whenmorethanonethreadiswai>ngforalockedmutex,whichthreadwill
begrantedthelockfirstaeritisreleased?
ANSWER:Unlessthreadpriorityscheduling(notcovered)isused,theassignmentwillbe
letothena>vesystemschedulerandmay
appeartobemoreorlessrandom.
69
Example:UsingMutexes
Serialversion:
hDps://compu>ng.llnl.gov/tutorials/pthreads/
samples/dotprod_serial.c
Pthreadsversion:
hDps://compu>ng.llnl.gov/tutorials/pthreads/samples/dotprod_mutex.c
70
3.Condi>onVariables
71
Overview
Condi>onvariablesprovideyetanotherwayforthreadstosynchronize.Whilemutexesimplementsynchroniza>onby
controllingthreadaccesstodata,condi>onvariablesallow
threadstosynchronizebasedupontheactualvalueofdata.
Withoutcondi>onvariables,theprogrammerwouldneedtohavethreadscon>nuallypolling(possiblyinacri>calsec>on),
tocheckifthecondi>onismet.Thiscanbeveryresourceconsumingsincethethreadwouldbecon>nuouslybusyin
thisac>vity.Acondi>onvariableisawaytoachievethesame
goalwithoutpolling.
Acondi>onvariableisalwaysusedinconjunc>onwithamutexlock.
72
-
8/6/2019 08_POSIX Threads Programming Class
19/21
4/25/11
19
Ar
epresenta>ve
sequence
forusingcondi>on
variables
MainThread
oeclareandini>alizeglobaldata/variableswhichrequiresynchroniza>on(suchas"count")
oeclareandini>alizeacondi>onvariableobjectoeclareandini>alizeanassociatedmutexoCreatethreadsAandBtodoworkThread
ooworkuptothepointwhereacertaincondi>onmustoccur(suchas"count"
mustreachaspecifiedvalue)
oLockassociatedmutexandcheckvalueofaglobalvariable
oCallpthread_cond_wait()toperformablockingwaitforsignalfromThread-B.
Notethatacalltopthread_cond_wait()
automa>callyandatomicallyunlocks
theassociatedmutexvariablesothatitcanbeusedbyThread-B.
oWhensignalled,wakeup.Mutexisautoma>callyandatomicallylocked.
oExplicitlyunlockmutexoCon>nue
ThreadB
ooworkoLockassociatedmutexoChangethevalueoftheglobalvariablethatThread-Aiswai>ngupon.
oCheckvalueoftheglobalThread-Awaitvariable.Ifitfulfillsthedesired
condi>on,signalThread-A.
oUnlockmutex.oCon>nue
MainThread
Join/Con>nue73
Crea;ngandDestroyingCondi;on
Variables
pthread_cond_init(condi;on,aAr) pthread_cond_destroy(condi;on) pthread_condaAr_init(aAr) pthread_condaAr_destroy(aAr)
74
Usage
Condi>onvariablesmustbedeclaredwithtypepthread_cond_t,andmustbeini>alizedbeforethey
canbeused.Therearetwowaystoini>alizea
condi>onvariable:
Sta>cally,whenitisdeclared.Forexample:pthread_cond_tmyconvar=PTHREA_CON_INITIALIZER;
ynamically,withthepthread_cond_init()rou>ne.TheIofthecreatedcondi>onvariableisreturnedtothecalling
threadthroughthe condi+onparameter.Thismethod
permitssengcondi>onvariableobjectaDributes,a5r.
75
Usage(cont.)
Theop>onala5robjectisusedtosetcondi>onvariableaDributes.ThereisonlyoneaDributedefinedforcondi>on
variables:process-shared,whichallowsthecondi>onvariable
tobeseenbythreadsinotherprocesses.TheaDributeobject,
ifused,mustbeoftypepthread_condaDr_t(maybespecified
asNULLtoacceptdefaults).Notethatnotallimplementa>ons
mayprovidetheprocess-sharedaDribute. Thepthread_condaDr_init()andpthread_condaDr_destroy()rou>nesareusedtocreateanddestroycondi>onvariable
aDributeobjects.
pthread_cond_destroy()shouldbeusedtofreeacondi>onvariablethatisnolongerneeded.
76
-
8/6/2019 08_POSIX Threads Programming Class
20/21
4/25/11
20
Wai;ngandSignalingon
Condi;onVariables
pthread_cond_wait(condi;on,mutex) pthread_cond_signal(condi;on) pthread_cond_broadcast(condi;on)
77
Usage
pthread_cond_wait()blocksthecallingthreadun>lthespecifiedcondi+onissignalled.Thisrou>neshouldbecalled
whilemutexislocked,anditwillautoma>callyreleasethe
mutexwhileitwaits.Aersignalisreceivedandthreadis
awakened,mutexwillbeautoma>callylockedforusebythe
thread.Theprogrammeristhenresponsibleforunlocking
mutexwhenthethreadisfinishedwithit.
Thepthread_cond_signal()rou>neisusedtosignal(orwakeup)anotherthreadwhichiswai>ngonthecondi>onvariable.
Itshouldbecalledaermutexislocked,andmustunlock
mutexinorderforpthread_cond_wait()rou>netocomplete.
Thepthread_cond_broadcast()rou>neshouldbeusedinsteadofpthread_cond_signal()ifmorethanonethreadisina
blockingwaitstate. 78
Usage(cont.)
Itisalogicalerrortocallpthread_cond_signal()beforecallingpthread_cond_wait().
Properlockingandunlockingoftheassociatedmutexvariableisessen>alwhenusingtheserou>nes.For
example:
Failingtolockthemutexbeforecallingpthread_cond_wait()maycauseitNOTtoblock.
Failingtounlockthemutexaercallingpthread_cond_signal()maynotallowamatching
pthread_cond_wait()rou>netocomplete(itwillremain
blocked).
79
Example:UsingCondi;on
Variables
hDps://compu>ng.llnl.gov/tutorials/pthreads/samples/condvar.c
80
-
8/6/2019 08_POSIX Threads Programming Class
21/21
4/25/11
21
Tutorialem
hDps://compu>ng.llnl.gov/tutorials/pthreads/
81