/
Monitors Deprecated Around the time concurrent programming was becoming a big de al object Monitors Deprecated Around the time concurrent programming was becoming a big de al object

Monitors Deprecated Around the time concurrent programming was becoming a big de al object - PDF document

karlyn-bohler
karlyn-bohler . @karlyn-bohler
Follow
550 views
Uploaded On 2014-12-18

Monitors Deprecated Around the time concurrent programming was becoming a big de al object - PPT Presentation

Not surprisi ngly peo ple started to think about ways to merge synchronization int o a more structured programming environment One such approach that emerged was the monitor First described by Per Brinch Hansen BH73 and later re64257ned by Tony Hoa ID: 25794

Not surprisi ngly peo

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "Monitors Deprecated Around the time conc..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

DMonitors(Deprecated)Aroundthetimeconcurrentprogrammingwasbecomingabigdeal,object-orientedprogrammingwasalsogainingground.Notsurprisingly,peo-plestartedtothinkaboutwaystomergesynchronizationintoamorestructuredprogrammingenvironment.Onesuchapproachthatemergedwasthemonitor.FirstdescribedbyPerBrinchHansen[BH73]andlaterrenedbyTonyHoare[H74],theideabehindamonitorisquitesimple.ConsiderthefollowingpretendmonitorwritteninC++notation:monitorclassaccount{private:intbalance=0;public:voiddeposit(intamount){balance=balance+amount;}voidwithdraw(intamount){balance=balance-amount;}};FigureD.1:APretendMonitorClassNote:thisisa“pretend”classbecauseC++doesnotsupportmoni-tors,andhencethemonitorkeyworddoesnotexist.However,Javadoessupportmonitors,withwhatarecalledsynchronizedmethods.Below,wewillexaminebothhowtomakesomethingquitelikeamonitorinC/C++,aswellashowtouseJavasynchronizedmethods.Inthisexample,youmaynoticewehaveouroldfriendtheaccountandsomeroutinestodepositandwithdrawanamountfromthebalance.Asyoualsomaynotice,thesearecriticalsections;iftheyarecalledbymultiplethreadsconcurrently,youhavearaceconditionandthepoten-tialforanincorrectoutcome.1 2MONITORS(DEPRECATED) Inamonitorclass,youdon'tgetintotrouble,though,becausethemonitorguaranteesthatonlyonethreadcanbeactivewithinthemon-itoratatime.Thus,ouraboveexampleisaperfectlysafeandworkingpieceofcode;multiplethreadscancalldeposit()orwithdraw()andknowthatmutualexclusionispreserved.Howdoesthemonitordothis?Simple:withalock.Wheneverathreadtriestocallamonitorroutine,itimplicitlytriestoacquirethemon-itorlock.Ifitsucceeds,thenitwillbeabletocallintotheroutineandrunthemethod'scode.Ifitdoesnot,itwillblockuntilthethreadthatisinthemonitornisheswhatitisdoing.Thus,ifwewroteaC++classthatlookedlikethefollowing,itwouldaccomplishtheexactsamegoalasthemonitorclassabove:classaccount{private:intbalance=0;pthread_mutex_tmonitor;public:voiddeposit(intamount){pthread_mutex_lock(&monitor);balance=balance+amount;pthread_mutex_unlock(&monitor);}voidwithdraw(intamount){pthread_mutex_lock(&monitor);balance=balance-amount;pthread_mutex_unlock(&monitor);}};FigureD.2:AC++ClassthatactslikeaMonitorThus,asyoucanseefromthisexample,themonitorisn'tdoingtoomuchforyouautomatically.Basically,itisjustacquiringalockandre-leasingit.Bydoingso,weachievewhatthemonitorrequires:onlyonethreadwillbeactivewithindeposit()orwithdraw(),asdesired.D.1WhyBotherwithMonitors?Youmightwonderwhymonitorswereinventedatall,insteadofjustusingexplicitlocking.Atthetime,object-orientedprogrammingwasjustcomingintofashion.Thus,theideawastogracefullyblendsomeofthekeyconceptsinconcurrentprogrammingwithsomeofthebasicapproachesofobjectorientation.Nothingmorethanthat.D.2DoWeGetMoreThanAutomaticLocking?OPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG MONITORS(DEPRECATED)3 monitorclassBoundedBuffer{private:intbuffer[MAX];intfill,use;intfullEntries=0;cond_tempty;cond_tfull;public:voidproduce(intelement){if(fullEntries==MAX)//lineP0wait(&empty);//lineP1buffer[fill]=element;//lineP2fill=(fill+1)%MAX;//lineP3fullEntries++;//lineP4signal(&full);//lineP5}intconsume(){if(fullEntries==0)//lineC0wait(&full);//lineC1inttmp=buffer[use];//lineC2use=(use+1)%MAX;//lineC3fullEntries--;//lineC4signal(&empty);//lineC5returntmp;//lineC6}}FigureD.3:Producer/ConsumerwithMonitorsandHoareSemanticsBacktobusiness.Asweknowfromourdiscussionofsemaphores,justhavinglocksisnotquiteenough;forexample,toimplementthepro-ducer/consumersolution,wepreviouslyusedsemaphorestobothputthreadstosleepwhenwaitingforaconditiontochange(e.g.,aproducerwaitingforabuffertobeemptied),aswellastowakeupathreadwhenaparticularconditionhaschanged(e.g.,aconsumersignalingthatithasindeedemptiedabuffer).Monitorssupportsuchfunctionalitythroughanexplicitconstructknownasaconditionvariable.Let'stakealookattheproducer/consumerso-lution,herewrittenwithmonitorsandconditionvariables.Inthismonitorclass,wehavetworoutines,produce()andconsume().Aproducerthreadwouldrepeatedlycallproduce()toputdataintotheboundedbuffer,whileaconsumer()wouldrepeatedlycallconsume().TheexampleisamodernparaphraseofHoare'ssolution[H74].Youshouldnoticesomesimilaritiesbetweenthiscodeandthesemaphore-basedsolutioninthepreviousnote.Onemajordifferenceishowcondi-c\r2008–19,ARPACI-DUSSEAUTHREEEASYPIECES 4MONITORS(DEPRECATED) tionvariablesmustbeusedinconcertwithanexplicitstatevariable;inthiscase,theintegerfullEntriesdetermineswhetheraproducerorconsumermustwait,dependingonitsstate.Semaphores,incontrast,haveaninternalnumericvaluewhichservesthissamepurpose.Thus,conditionvariablesmustbepairedwithsomekindofexternalstatevalueinordertoachievethesameend.Themostimportantaspectofthiscode,however,istheuseofthetwoconditionvariables,emptyandfull,andtherespectivewait()andsignal()callsthatemploythem.Theseoperationsdoexactlywhatyoumightthink:wait()blocksthecallingthreadonagivencondition;signal()wakesonewaitingthreadthatiswaitingonthecondition.However,therearesomesubtletiesinhowthesecallsoperate;under-standingthesemanticsofthesecallsiscriticallyimportanttounderstand-ingwhythiscodeworks.InwhatresearchersinoperatingsystemscallHoaresemantics(yes,asomewhatunfortunatename),thesignal()immediatelywakesonewaitingthreadandrunsit;thus,themonitorlock,whichisimplicitlyheldbytherunningthread,immediatelyistrans-ferredtothewokenthreadwhichthenrunsuntiliteitherblocksorex-itsthemonitor.Notethattheremaybemorethanonethreadwaiting;signal()onlywakesonewaitingthreadandrunsit,whiletheothersmustwaitforasubsequentsignal.Asimpleexamplewillhelpusunderstandthiscodebetter.Imaginetherearetwothreads,oneaproducerandtheotheraconsumer.Thecon-sumergetstorunrst,andcallsconsume(),onlytondthatfullEntries=0(C0),asthereisnothinginthebufferyet.Thus,itcallswait(&full)(C1),andwaitsforabuffertobelled.Theproducerthenruns,ndsitdoesn'thavetowait(P0),putsanelementintothebuffer(P2),in-crementsthellindex(P3)andthefullEntriescount(P4),andcallssignal(&full)(P5).InHoaresemantics,theproducerdoesnotcon-tinuerunningafterthesignal;rather,thesignalimmediatelytransferscontroltothewaitingconsumer,whichreturnsfromwait()(C1)andimmediatelyconsumestheelementproducedbytheproducer(C2)andsoon.Onlyaftertheconsumerreturnswilltheproducergettorunagainandreturnfromtheproduce()routine.D.3WhereTheoryMeetsPracticeTonyHoare,whowrotethesolutionaboveandcameupwiththeex-actsemanticsforsignal()andwait(),wasatheoretician.Clearlyasmartguy,too;hecameupwithquicksortafterall[H61].However,thesemanticsofsignalingandwaiting,asitturnsout,werenotidealforarealimplementation.Astheoldsayinggoes,intheory,thereisnodiffer-encebetweentheoryandpractice,butinpractice,thereis.OPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG MONITORS(DEPRECATED)5 OLDAYING:THEORYVS.PRACTICETheoldsayingis“intheory,thereisnodifferencebetweentheoryandpractice,butinpractice,thereis.”Ofcourse,onlypractitionerstellyouthis;atheorypersoncouldundoubtedlyprovethatitisnottrue.Afewyearslater,ButlerLampsonandDavidRedellofXeroxPARCwerebuildingaconcurrentlanguageknownasMesa,anddecidedtousemonitorsastheirbasicconcurrencyprimitive[LR80].Theywerewell-knownsystemsresearchers,andtheysoonfoundthatHoaresemantics,whilemoreamenabletoproofs,werehardtorealizeinarealsystem(therearealotofreasonsforthis,perhapstoomanytogothroughhere).Inparticular,tobuildaworkingmonitorimplementation,LampsonandRedelldecidedtochangethemeaningofsignal()inasubtlebutcrit-icalway.Thesignal()routinenowwasjustconsideredahint[L83];itwouldmoveasinglewaitingthreadfromtheblockedstatetoarunnablestate,butitwouldnotrunitimmediately.Rather,thesignalingthreadwouldretaincontroluntilitexitedthemonitorandwasdescheduled.D.4OhOh,ARaceGiventhesenewMesasemantics,letusagainreexaminethecodeabove.Imagineagainaconsumer(consumer1)whoentersthemoni-torandndsthebufferemptyandthuswaits(C1).Nowtheproducercomesalongandllsthebufferandsignalsthatabufferhasbeenlled,movingthewaitingconsumerfromblockedonthefullconditionvariabletoready.Theproducerkeepsrunningforawhile,andeventuallygivesuptheCPU.ButHouston,wehaveaproblem.Canyouseeit?Imagineadiffer-entconsumer(consumer2)nowcallsintotheconsume()routine;itwillndafullbuffer,consumeit,andreturn,settingfullEntriesto0inthemeanwhile.Canyouseetheproblemyet?Well,hereitcomes.Ouroldfriendconsumer1nownallygetstorun,andreturnsfromwait(),ex-pectingabuffertobefull(C1...);unfortunately,thisisnolongertrue,asconsumer2snuckinandconsumedthebufferbeforeconsumer1hadachancetoconsumeit.Thus,thecodedoesn'twork,becauseinthetimebetweenthesignal()bytheproducerandthereturnfromwait()bycon-sumer1,theconditionhaschanged.Thistimelineillustratestheproblem:Fortunately,theswitchfromHoaresemanticstoMesasemanticsre-quiresonlyasmallchangebytheprogrammertorealizeaworkingso-lution.Specically,whenwoken,athreadshouldrechecktheconditionitwaswaitingon;becausesignal()isonlyahint,itispossiblethattheconditionhaschanged(evenmultipletimes)andthusmaynotbeinthedesiredstatewhenthewaitingthreadruns.Inourexample,twolinesofcodemustchange,linesP0andC0:c\r2008–19,ARPACI-DUSSEAUTHREEEASYPIECES 6MONITORS(DEPRECATED) ProducerConsumer1Consumer2C0(fullEnt=0)C1(Con1:blocked)P0(fullEnt=0)P2P3P4(fullEnt=1)P5(Con1:ready)C0(fullEnt=1)C2C3C4(fullEnt=0)C5C6C2(usingabuffer,fullEnt=0!)FigureD.4:WhytheCodedoesn'tworkwithHoareSemanticspublic:voidproduce(intelement){while(fullEntries==MAX)//lineP0(CHANGEDIF-�WHILE)wait(&empty);//lineP1buffer[fill]=element;//lineP2fill=(fill+1)%MAX;//lineP3fullEntries++;//lineP4signal(&full);//lineP5}intconsume(){while(fullEntries==0)//lineC0(CHANGEDIF-�WHILE)wait(&full);//lineC1inttmp=buffer[use];//lineC2use=(use+1)%MAX;//lineC3fullEntries--;//lineC4signal(&empty);//lineC5returntmp;//lineC6}FigureD.5:Producer/ConsumerwithMonitorsandMesaSemanticsNottoohardafterall.Becauseoftheeaseofthisimplementation,virtuallyanysystemtodaythatusesconditionvariableswithsignalingandwaitingusesMesasemantics.Thus,ifyouremembernothingelseatallfromthisclass,youcanjustremember:alwaysrechecktheconditionafterbeingwoken!Putinevensimplerterms,usewhileloopsandnotifstatementswhencheckingconditions.Notethatthisisalwayscorrect,evenifsomehowyouarerunningonasystemwithHoaresemantics;inOPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG MONITORS(DEPRECATED)7 t|Con1Con2Prod|Mon|Empty|Full|FE|Comment------------------------------------------------------------------------0C001C1Con10Con1waitingonfull2Contextswitch&#x-0.0;颉眀Con10switch:Con1toProd3P0Con104P2Con10Proddoesn'twait(FE=0)5P3Con106P4Con11ProdupdatesfullEntries7P51Prodsignals:Con1nowready8Contextswitch&#x-0.0;颉眀1switch:ProdtoCon29C01switchtoCon210C21Con2doesn'twait(FE=1)11C3112C40Con2changesfullEntries13C50Con2signalsempty(nowaiter)14C60Con2done15Contextswitch&#x-0.0;颉眀0switch:Con2toCon116C00recheckfullEntries:0!17C1Con10waitonfullagainFigureD.6:TracingQueuesduringaProducer/ConsumerRunthatcase,youwouldjustneedlesslyretesttheconditionanextratime.D.5PeekingUnderTheHoodABitTounderstandabitbetterwhyMesasemanticsareeasiertoimple-ment,let'sunderstandalittlemoreabouttheimplementationofMesamonitors.Intheirwork[LR80],LampsonandRedelldescribethreediffer-enttypesofqueuesthatathreadcanbeapartofatagiventime:thereadyqueue,amonitorlockqueue,andaconditionvariablequeue.Notethataprogrammighthavemultiplemonitorclassesandmultipleconditionvariableinstances;thereisaqueueperinstanceofsaiditems.Withasingleboundedbuffermonitor,wethushavefourqueuestoconsider:thereadyqueue,asinglemonitorqueue,andtwoconditionvariablequeues(oneforthefullconditionandonefortheempty).Tbetterunderstandhowathreadlibrarymanagesthesequeues,whatwewilldoisshowhowathreadtransitionsthroughthesequeuesinthepro-ducer/consumerexample.Inthisexample,wewalkthroughacasewhereaconsumermightbewokenupbutndthatthereisnothingtoconsume.Letusconsiderthefollowingtimeline.Ontheleftaretwoconsumers(Con1andCon2)andaproducer(Prod)andwhichlineofcodetheyareexecuting;ontherightisthestateofeachofthefourqueueswearefollowingforthisexample:thereadyqueueofrunnableprocesses,themonitorlockqueuecalledMonitor,andtheemptyandfullconditionvariablequeues.Wealsotracktime(t),thethreadthatisrunning(squarebracketsaroundthethreadonthereadyqueuethatisrunning),andthevalueoffullEntries(FE).Asyoucanseefromthetimeline,consumer2(Con2)sneaksinandconsumestheavailabledata(t=9..14)beforeconsumer1(Con1),whowasc\r2008–19,ARPACI-DUSSEAUTHREEEASYPIECES 8MONITORS(DEPRECATED) monitorclassallocator{intavailable;//howmuchmemoryisavailable?cond_tc;void*allocate(intsize){while(size�available)wait(&c);available-=size;//andthendowhatevertheallocatorshoulddo//andreturnachunkofmemory}voidfree(void*pointer,intsize){//freeupsomememoryavailable+=size;signal(&c);}};FigureD.7:ASimpleMemoryAllocatorwaitingonthefullconditiontobesignaled(sincet=1),getsachancetodoso.However,Con1doesgetwokenbytheproducer'ssignal(t=7),andthusrunsagaineventhoughthebufferisemptybythetimeitdoesso.IfCon1didn'trecheckthestatevariablefullEntries(t=16),itwouldhaveerroneouslytriedtoconsumedatawhennodatawaspresenttconsume.Thus,thisnaturalimplementationisexactlywhatleadsustoMesasemantics(andnotHoare).D.6OtherUsesOfMonitorsIntheirpaperonMesa,LampsonandRedellalsopointoutafewplaceswhereadifferentkindofsignalingisneeded.Forexample,con-siderthefollowingmemoryallocator(FigureD.7).Manydetailsareleftoutofthisexample,inordertoallowustofocusontheconditionsforwakingandsignaling.Itturnsoutthesignal/waitcodeabovedoesnotquitework;canyouseewhy?Imaginetwothreadscallallocate.Therstcallsallocate(20)andthesecondallocate(10).Nomemoryisavailable,andthusboththreadscallwait()andblock.Sometimelater,adifferentthreadcomesalongandcallsfree(p,15),andthusfreesup15bytesofmemory.Itthensignalsthatithasdoneso.Unfortunately,itwakesthethreadwaitingfor20bytes;thatthreadrechecksthecondition,ndsthatonly15bytesareavailable,andcallswait()again.Thethreadthatcouldhavebenetedfromthefreeof15bytes,i.e.,thethreadthatcalledallocate(10),isnotwoken.LampsonandRedellsuggestasimplesolutiontothisproblem.In-steadofasignal()whichwakesasinglewaitingthread,theyemployabroadcast()whichwakesallwaitingthreads.Thus,allthreadsarewokenOPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG MONITORS(DEPRECATED)9 monitorclassSemaphore{ints;//valueofthesemaphoreSemaphore(intvalue){s=value;}voidwait(){while(s=0)wait();s--;}voidpost(){s++;signal();}};FigureD.8:ImplementingaSemaphorewithaMonitorup,andintheexampleabove,thethreadwaitingfor10byteswillnd15availableandsucceedinitsallocation.InMesasemantics,usingabroadcast()isalwayscorrect,asallthreadsshouldrechecktheconditionofinterestuponwakinganyhow.However,itmaybeaperformanceproblem,andthusshouldonlybeusedwhenneeded.Inthisexample,abroadcast()mightwakehundredsofwaitingthreads,onlytohaveonesuccessfullycontinuewhiletherestimmedi-atelyblockagain;thisproblem,sometimesknownasathunderingherd,iscostly,duetoalltheextracontextswitchesthatoccur.D.7UsingMonitorsToImplementSemaphoresYoucanprobablyseealotofsimilaritiesbetweenmonitorsandsemaphores.Notsurprisingly,youcanuseonetoimplementtheother.Here,weshowhowyoumightimplementasemaphoreclassusingamonitor(FigureD.8).Asyoucansee,wait()simplywaitsforthevalueofthesemaphoretbegreaterthan0,andthendecrementsitsvalue,whereaspost()incre-mentsthevalueandwakesonewaitingthread(ifthereisone).It'sassimpleasthat.Tousethisclassasabinarysemaphore(i.e.,alock),youjustinitializethesemaphoreto1,andthenputwait()/post()pairsaroundcriticalsec-tions.Andthuswehaveshownthatmonitorscanbeusedtoimplementsemaphores.D.8MonitorsintheRealWorldc\r2008–19,ARPACI-DUSSEAUTHREEEASYPIECES 10MONITORS(DEPRECATED) classBoundedBuffer{private:intbuffer[MAX];intfill,use;intfullEntries;pthread_mutex_tmonitor;//monitorlockpthread_cond_tempty;pthread_cond_tfull;public:BoundedBuffer(){use=fill=fullEntries=0;}voidproduce(intelement){pthread_mutex_lock(&monitor);while(fullEntries==MAX)pthread_cond_wait(&empty,&monitor);buffer[fill]=element;fill=(fill+1)%MAX;fullEntries++;pthread_cond_signal(&full);pthread_mutex_unlock(&monitor);}intconsume(){pthread_mutex_lock(&monitor);while(fullEntries==0)pthread_cond_wait(&full,&monitor);inttmp=buffer[use];use=(use+1)%MAX;fullEntries--;pthread_cond_signal(&empty);pthread_mutex_unlock(&monitor);returntmp;}}FigureD.9:C++Producer/Consumerwitha“Monitor”Wealreadymentionedabovethatwewereusing“pretend”monitors;C++hasnosuchconcept.Wenowshowhowtomakeamonitor-likeC++class,andhowJavausessynchronizedmethodstoachieveasimilarend.AC++MonitorofSortsHereistheproducer/consumercodewritteninC++withlocksandcon-ditionvariables(FigureD.9).YoucanseeinthiscodeexamplethatthereOPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG MONITORS(DEPRECATED)11 islittledifferencebetweenthepretendmonitorcodeandtheworkingC++classwehaveabove.Ofcourse,oneobviousdifferenceistheexplicituseofalock”monitor”.MoresubtleistheswitchtothePOSIXstandardpthread cond signal()andpthread cond wait()calls.Inpartic-ular,noticethatwhencallingpthread cond wait(),onealsopassesinthelockthatisheldatthetimeofwaiting.Thelockisneededinsidepthread cond wait()becauseitmustbereleasedwhenthisthreadisputtosleepandre-acquiredbeforeitreturnstothecaller(thesamebe-havioraswithinamonitorbutagainwithexplicitlocks).AJavaMonitorInterestingly,thedesignersofJavadecidedtousemonitorsastheythoughttheywereagracefulwaytoaddsynchronizationprimitivesintoalan-guage.Tousethem,youjustuseaddthekeywordsynchronizedtothemethodorsetofmethodsthatyouwishtouseasamonitor(hereisanexamplefromSun'sowndocumentationsite[S12a,S12b]):Thiscodedoesexactlywhatyouthinkitshould:provideacounterthatisthreadsafe.Becauseonlyonethreadisallowedintothemonitoratatime,onlyonethreadcanupdatethevalueof”c”,andthusaraceconditionisaverted.JavaandtheSingleConditionVariableIntheoriginalversionofJava,aconditionvariablewasalsosuppliedwitheachsynchronizedclass.Touseit,youwouldcalleitherwait()ornotify()(sometimesthetermnotifyisusedinsteadofsignal,buttheymeanthesamething).Oddlyenough,inthisoriginalimplementation,therewasnowaytohavetwo(ormore)conditionvariables.Youmayhavenoticedintheproducer/consumersolution,wealwaysusetwo:oneforsignalingabufferhasbeenemptied,andanotherforsignalingthatabufferhasbeenlled.Tounderstandthelimitationsofonlyprovidingasingleconditionvariable,let'simaginetheproducer/consumersolutionwithonlyasin-gleconditionvariable.Imaginetwoconsumersrunrst,andbothgetstuckwaiting.Then,aproducerruns,llsasinglebuffer,wakesasingleconsumer,andthentriestollagainbutndsthebufferfull(MAX=1).Thus,wehaveaproducerwaitingforanemptybuffer,aconsumerwait-ingforafullbuffer,andaconsumerwhohadbeenwaitingabouttorunbecauseithasbeenwoken.Theconsumerthenrunsandconsumesthebuffer.Whenitcallsno-tify(),though,itwakesasinglethreadthatiswaitingonthecondition.Becausethereisonlyasingleconditionvariable,theconsumermightwakethewaitingconsumer,insteadofthewaitingproducer.Thus,thesolutiondoesnotwork.Toremedythisproblem,onecanagainusethebroadcastsolution.InJava,onecallsnotifyAll()towakeallwaitingthreads.Inthiscase,thec\r2008–19,ARPACI-DUSSEAUTHREEEASYPIECES 12MONITORS(DEPRECATED) publicclassSynchronizedCounter{privateintc=0;publicsynchronizedvoidincrement(){c++;}publicsynchronizedvoiddecrement(){c--;}publicsynchronizedintvalue(){returnc;}}FigureD.10:ASimpleJavaClasswithSynchronizedMethodsconsumerwouldwakeaproducerandaconsumer,buttheconsumerwouldndthatfullEntriesisequalto0andgobacktosleep,whiletheproducerwouldcontinue.Asusual,wakingallwaiterscanleadtothethunderingherdproblem.Becauseofthisdeciency,JavalateraddedanexplicitConditionclass,thusallowingforamoreefcientsolutiontothisandothersimilarcon-currencyproblems.D.9SummaryWehaveseentheintroductionofmonitors,astructuringconceptde-velopedbyBrinchHansenandandsubsequentlyHoareintheearlysev-enties.Whenrunninginsidethemonitor,athreadimplicitlyholdsamon-itorlock,andthuspreventsotherthreadsfromenteringthemonitor,al-lowingthereadyconstructionofmutualexclusion.Wealsohaveseentheintroductionofexplicitconditionvariables,whichallowthreadstosignal()andwait()muchlikewesawwithsemaphoresinthepreviousnote.Thesemanticsofsignal()andwait()arecritical;be-causeallmodernsystemsimplementMesasemantics,arecheckoftheconditionthatthethreadwenttosleeponisrequiredforcorrectexecu-tion.Thus,signal()isjustahintthatsomethinghaschanged;itistheresponsibilityofthewokenthreadtomakesuretheconditionsarerightforitscontinuedexecution.Finally,becauseC++hasnomonitorsupport,wesawhowtoemulatemonitorswithexplicitpthreadlocksandconditionvariables.WealsosawhowJavasupportsmonitorswithitssynchronizedroutines,andsomeofthelimitationsofonlyprovidingasingleconditionvariableinsuchanenvironment.OPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG MONITORS(DEPRECATED)13 References[BH73]“OperatingSystemPrinciples”PerBrinchHansen,Prentice-Hall,1973Available:http://portal.acm.org/citation.cfm?id=540365Oneoftherstbooksonoperatingsystems;certainlyaheadofitstime.Introducedmonitorsasaconcurrencyprimitive.[H74]“Monitors:AnOperatingSystemStructuringConcept”C.A.R.HoareCACM,Volume17:10,pages549–557,October1974Anearlyreferencetomonitors;however,BrinchHansenprobablywasthetrueinventor.[H61]“Quicksort:Algorithm64”C.A.R.HoareCACM,Volume4:7,July1961Thefamousquicksortalgorithm.[LR80]“ExperiencewithProcessesandMonitorsinMesa”B.W.LampsonandD.R.RedellCACM,Volume23:2,pages105–117,February1980Anearlyandimportantpaperhighlightingthedifferencesbetweentheoryandpractice.[L83]“HintsforComputerSystemsDesign”ButlerLampsonACMOperatingSystemsReview,15:5,October1983Lampson,afamoussystemsresearcher,lovedusinghintsinthedesignofcomputersystems.Ahintissomethingthatisoftencorrectbutcanbewrong;inthisuse,asignal()istellingawaitingthreadthatitchangedtheconditionthatthewaiterwaswaitingon,butnottotrustthattheconditionwillbeinthedesiredstatewhenthewaitingthreadwakesup.Inthispaperabouthintsfordesigningsystems,oneofLampson'sgeneralhintsisthatyoushouldusehints.Itisnotasconfusingasitsounds.[S12a]“SynchronizedMethods”Sundocumentationhttp://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.html[S12b]“ConditionInterface”Sundocumentationhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/Condition.htmlc\r2008–19,ARPACI-DUSSEAUTHREEEASYPIECES