版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
1Chapter5MutualExclusion(互斥)andSynchronization(同步)
OperatingSystems2Agenda5.1PrinciplesofConcurrency5.2MutualExclusion:HardwareSupport5.3Semaphores5.4Monitors5.5MessagePassing5.6Readers/WritersProblem5.7Summary3ConcurrencyConcurrencyarisesinthreedifferentcontexts:Multipleapplications(多應(yīng)用程序)MultiprogrammingStructuredapplication(結(jié)構(gòu)化應(yīng)用程序)SomeapplicationcanbedesignedasasetofconcurrentprocessesOperating-systemstructure(操作系統(tǒng)結(jié)構(gòu))Operatingsystemisasetofprocessesorthreads4Concurrency臨界區(qū)死鎖活鎖互斥競爭條件饑餓55.1PrinciplesofConcurrency5.1.1ASimpleExample5.1.2RaceCondition5.1.3OperatingSystemConcerns5.1.4ProcessInteraction5.1.5RequirementsforMutualExclusion6DifficultiesofConcurrencySharingofglobalresourcesOperatingsystemmanagingtheallocationofresourcesoptimallyDifficulttolocateprogrammingerrors7ASimpleExamplecharchin,chout;voidecho(){ chin=getchar(); chout=chin; putchar(chout);}8ASimpleExample(Uniprocessor)
ProcessP1 ProcessP2. . chin=getchar(); .chout=chin; . chin=getchar(); chout=chin;putchar(chout);putchar(chout); .. .9ASimpleExample(Multiprocessor)
ProcessP1 ProcessP2. . chin=getchar(); .. chin=getchar();chout=chin; chout=chin;putchar(chout); .. putchar(chout);. .105.1PrinciplesofConcurrency5.1.1ASimpleExample5.1.2RaceCondition5.1.3OperatingSystemConcerns5.1.4ProcessInteraction5.1.5RequirementsforMutualExclusion11RaceCondition(競爭條件)Araceconditionoccurswhenmultipleprocessesorthreadsreadandwritedataitemssothatthefinalresultdependsontheorderofexecutionofinstructionsinthemultipleprocessesorthread.(競爭條件發(fā)生在當(dāng)多個進(jìn)程或者線程在讀寫數(shù)據(jù)時,其最終結(jié)果依賴于多個進(jìn)程或者線程的指令執(zhí)行順序)125.1PrinciplesofConcurrency5.1.1ASimpleExample5.1.2RaceCondition5.1.3OperatingSystemConcerns5.1.4ProcessInteraction5.1.5RequirementsforMutualExclusion13OperatingSystemConcernsKeeptrackofvariousprocesses(throughPCB)AllocateanddeallocateresourcesProcessortimeMemoryFilesI/OdevicesProtectdataandresourcesOutputofprocessmustbeindependentofthespeedofexecutionofotherconcurrentprocesses145.1PrinciplesofConcurrency5.1.1ASimpleExample5.1.2RaceCondition5.1.3OperatingSystemConcerns5.1.4ProcessInteraction5.1.5RequirementsforMutualExclusion15ProcessInteraction(進(jìn)程交互)ProcessesunawareofeachotherProcessesindirectlyawareofeachotherProcessdirectlyawareofeachother1617CompetitionAmongProcessesforResources(進(jìn)程間的資源爭用)MutualExclusion(互斥)CriticalsectionsOnlyoneprogramatatimeisallowedinitscriticalsectionExampleonlyoneprocessatatimeisallowedtosendcommandtotheprinterDeadlock(死鎖)Starvation(饑餓)18IllustrationofMutualExclusionbycriticalsection.entercritical:進(jìn)入臨界區(qū).exitcritical:退出臨界區(qū)195.1PrinciplesofConcurrency5.1.1ASimpleExample5.1.2RaceCondition5.1.3OperatingSystemConcerns5.1.4ProcessInteraction5.1.5RequirementsforMutualExclusion20RequirementsforMutualExclusionOnlyoneprocessatatimeisallowedinthecriticalsectionforaresource(一次只允許一個進(jìn)程進(jìn)入臨界區(qū),忙則等待)Aprocessthathaltsinitsnoncriticalsectionmustdosowithoutinterferingwithotherprocesses(阻塞于臨界區(qū)外的進(jìn)程不能干涉其它進(jìn)程)Nodeadlockorstarvation(不會發(fā)生饑餓和死鎖,有限等待)21RequirementsforMutualExclusionAprocessmustnotbedelayedaccesstoacriticalsectionwhenthereisnootherprocessusingit(閑則讓進(jìn))Noassumptionsaremadeaboutrelativeprocessspeedsornumberofprocesses(對相關(guān)進(jìn)程的執(zhí)行速度和處理器數(shù)目沒有要求)Aprocessremainsinsideitscriticalsectionforafinitetimeonly(有限占用)22Agenda5.1PrinciplesofConcurrency5.2MutualExclusion:HardwareSupport5.3Semaphores5.4Monitors5.5MessagePassing5.6Readers/WritersProblem5.7Summary235.2MutualExclusion:HardwareSupport5.2.1InterruptDisabling(中斷禁止)5.2.2SpecialMachineInstructions(特殊機(jī)器指令)24HardwareSupport:InterruptDisabling25AprocessrunsuntilitinvokesanoperatingsystemserviceoruntilitisinterruptedDisablinginterruptsguaranteesmutualexclusiononuniprocessorsystemDisadvantage:Processorislimitedinitsabilitytointerleaveprogramsdisablinginterruptsononeprocessorwillnotguaranteemutualexclusioninmulti-processorsenvironment.HardwareSupport:InterruptDisabling265.2MutualExclusion:HardwareSupport5.2.1InterruptDisabling5.2.2SpecialMachineInstructions27PerformedinasingleinstructioncycleAccesstothememorylocationisblockedforanyotherinstructionsHardwareSupport:SpecialMachineInstructions28TestandSetInstruction(textedition5) booleantestset(inti){ if(i==0){ i=1; returntrue; } else{ returnfalse; } }HardwareSupport:SpecialMachineInstructions29Compareandswapintcompare_and_swap(int*word,inttestval,intnewval){ intoldval; oldval=*word; if(oldval==testval)*word=newval; returnoldval;}HardwareSupport:SpecialMachineInstructions30HardwareSupportforMutualExclusion31ExchangeInstruction voidexchange(intregister, intmemory){ inttemp; temp=memory; memory=register; register=temp; }HardwareSupport:SpecialMachineInstructions32HardwareSupportforMutualExclusion注意:第5版教材錯誤33AdvantagesBysharingmainmemory,itisapplicabletoanynumberofprocessessingleprocessormultipleprocessorsItissimpleandthereforeeasytoverifyItcanbeusedtosupportmultiplecriticalsectionsHardwareSupport:SpecialMachineInstructions34DisadvantagesBusy-waiting(忙等待)consumesprocessortimeStarvation(饑餓)ispossiblewhenaprocessleavesacriticalsectionandmorethanoneprocessiswaiting.Deadlock(死鎖)ispossibleIfalowpriorityprocesshasthecriticalregionandahigherpriorityprocessneeds,thehigherpriorityprocesswillobtaintheprocessortowaitforthecriticalregionHardwareSupport:SpecialMachineInstructions35Agenda5.1PrinciplesofConcurrency5.2MutualExclusion:HardwareSupport5.3Semaphores5.4Monitors5.5MessagePassing5.6Readers/WritersProblem5.7Summary365.3Semaphores5.3.1Overview5.3.2MutualExclusion5.3.3TheProducer/ConsumerProblem5.3.4ImplementofSemaphores37Semaphores(信號量)Fundamentalprinciple(基本原理):Twoormoreprocessescancooperatebymeansofsimplesignals,suchthataprocesscanbeforcedtostopataspecifiedplaceuntilithasreceivedaspecificsignal.(兩個或者多個進(jìn)程可以通過簡單的信號進(jìn)行合作,一個進(jìn)程可以被迫在一個位置停止,直到它收到一個信號)Forsignaling,specialvariablescalledsemaphoresareused(一種稱為信號量的特殊變量用來傳遞信號)Ifaprocessiswaitingforasignal,itissuspendeduntilthatsignalissent(如果一個進(jìn)程在等待一個信號,它會被掛起,直到它等待的信號被發(fā)出)38SemaphoresSemaphoreisavariablethathasanintegervalue(整數(shù)值)Initialize:Maybeinitializedtoanonnegativenumber(非負(fù)數(shù))semWait(P):Waitoperationdecrementsthesemaphorevalue,Ifthevaluebecomesnegative,thentheprocessexecutingthesemWaitisblocked.semSignal(V):Signaloperationincrementssemaphorevalue,Iftheresultingvalueislessthanorequaltozero,thenaprocessblockedbyasemWaitoperation,ifany,isunblocked.39SemaphorePrimitives(原語,原子操作)40BinarySemaphore(二元信號量)BinarySemaphoreisavariablethathasanintegervalueMaybeinitializedto0or1.semWaitB:checksthesemaphorevalue.Ifthevalueiszero,thentheprocessexecutingthesemWaitBisblocked.Ifthevalueisone,thenthevalueischangedtozeroandtheprocesscontinuesexecution.semSignalB:checkstoseeifanyprocessesareblockedonthis
semaphore.Ifso,thenaprocessblockedbya
semWaitBoperationisunblocked.Ifnoprocessesareblocked,thenthevalue
ofthesemaphoreissettoone.41BinarySemaphore(二元信號量)Primitives(原語)42Semaphoreterms(信號量術(shù)語)BinarySemaphore(二元信號量)Mutex(互斥信號量)CountingSemaphore(計數(shù)信號量)GeneralSemaphore(一般信號量)WeakSemaphore(弱信號量)StrongSemaphore(強(qiáng)信號量)435.3Semaphores5.3.1Overview5.3.2MutualExclusion5.3.3TheProducer/ConsumerProblem5.3.4ImplementofSemaphores44MutualExclusionUsingSemaphores45-1-2-146Morethanoneprocessinitscriticalsectionatatime(多個進(jìn)程同時在臨界區(qū)內(nèi))Initializethesemaphoretothespecifiedvalues.count>=0:s.countisthenumberofprocessesthatcanexecutesemWait(s)withoutsuspensions.count<0:Themagnitudeofs.countisthenumberofprocessessuspendedins.queue.475.3Semaphores5.3.1Overview5.3.2MutualExclusion5.3.3TheProducer/ConsumerProblem5.3.4ImplementofSemaphores48Producer/ConsumerProblem(生產(chǎn)者/消費(fèi)者問題)OneormoreproducersaregeneratingdataandplacingtheseinabufferAsingleconsumeristakingitemsoutofthebufferoneattimeOnlyoneproducerorconsumermayaccessthebufferatanyonetime49Producer/ConsumerProblemwithInfiniteBuffer(無限緩沖區(qū))50ProducerwithInfiniteBufferproducer:while(true){ /*produceitemv*/ b[in]=v; in++;}51ConsumerwithInfiniteBufferconsumer:while(true){ while(in<=out) /*donothing*/; w=b[out]; out++; /*consumeitemw*/}52控制進(jìn)入臨界區(qū)避免“超前”消費(fèi)緩沖區(qū)中的項數(shù)535455控制進(jìn)入臨界區(qū)控制“超前消費(fèi)”56Producer/ConsumerProblemwithFiniteBuffer(有限緩沖區(qū))57Producer/ConsumerProblemwithFiniteBuffer(有限緩沖區(qū))Thebufferistreatedasacircularstorage,andpointervaluesmustbeexpressedmodulothesizeofthebuffer.Thefollowingrelationshipshold:58ProducerwithCircularBufferproducer:while(true){ /*produceitemv*/ while((in+1)%n==out) /*donothing*/; b[in]=v; in=(in+1)%n}59ConsumerwithCircularBufferconsumer:while(true){ while(in==out) /*donothing*/; w=b[out]; out=(out+1)%n; /*consumeitemw*/}60控制進(jìn)入臨界區(qū)控制“超前”消費(fèi)控制生產(chǎn)“過剩”615.3Semaphores5.3.1Overview5.3.2MutualExclusion5.3.3TheProducer/ConsumerProblem5.3.4ImplementofSemaphores625.3.4ImplementofSemaphoresImplementinhardwareorfirmware(固件)Implementinsoftware,e.g.DekkerorPetersonImplementbyinhibitinterrupts(中斷禁止)forasingle-processorsystem635.3.4ImplementofSemaphores64Agenda5.1PrinciplesofConcurrency5.2MutualExclusion:HardwareSupport5.3Semaphores5.4Monitors5.5MessagePassing5.6Readers/WritersProblem5.7Summary65Monitors(管程)Monitorisasoftwaremoduleconsistingofoneoremoreprocedures,aninitializationsequence,andlocaldata(管程由一個或者多個例程、一段初始化代碼和局部數(shù)據(jù)組成).Andthechiefcharacteristicsarethefollowing:LocaldatavariablesareaccessibleonlybythemonitorProcessentersmonitorbyinvokingoneofitsproceduresOnlyoneprocessmaybeexecutinginthemonitoratatime66MonitorsOperations(管程操作)Amonitorsupportssynchronizationbytheuseofconditionvariables(管程通過條件變量實(shí)現(xiàn)同步)cwait(c):Suspendexecutionofthecallingprocessonconditionc.Themonitorisnowavailableforusebyanotherprocess.csignal(c):Resumeexecutionofsomeprocessblockedafteracwaitonthesamecondition.Ifthereareseveralsuchprocesses,chooseoneofthem;ifthereisnosuchprocess,donothing.Notethatmonitorwaitandsignaloperationsaredifferentfromthoseforthesemaphore.Ifaprocessinamonitorsignalsandnotaskiswaitingontheconditionvariable,thesignalislost.67686970Agenda5.1PrinciplesofConcurrency5.2MutualExclusion:HardwareSupport5.3Semaphores5.4Monitors5.5MessagePassing5.6Readers/WritersProblem5.7Summary71MessagePassingEnforcemutualexclusionExchangeinformation
send(destination,message) receive(source,message)72SynchronizationSenderandreceivermayormaynotbeblockingBlockingsend,blockingreceiveBothsenderandreceiverareblockeduntilmessageisdelivered73SynchronizationNonblockingsend,blockingreceiveSendercontinuesonReceiverisblockeduntiltherequestedmessagearrivesNonblockingsend,nonblockingreceiveNeitherpa
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024民法典運(yùn)輸合同風(fēng)險控制與管理協(xié)議3篇
- 商業(yè)航天產(chǎn)業(yè)園項目計劃書
- 2024年簡化版在線合同3篇
- 2024年車輛租賃協(xié)議標(biāo)準(zhǔn)格式
- 2024年融資租賃合同修正案
- 2024年風(fēng)險預(yù)警信息響應(yīng)與處理操作合同版
- 2024年藝人經(jīng)紀(jì)合同:影視作品參與協(xié)議3篇
- 2024智能法律咨詢與服務(wù)合同
- 2024年財務(wù)分析師合作合同3篇
- 2024年貸款支付購銷合同范本:國際貿(mào)易代理服務(wù)合同3篇
- ISO 56001-2024《創(chuàng)新管理體系-要求》專業(yè)解讀與應(yīng)用實(shí)踐指導(dǎo)材料之22:“8運(yùn)行-8.1運(yùn)行策劃和控制”(雷澤佳編制-2025B0)
- 2024-2030年中國硅肥行業(yè)規(guī)模分析及投資前景研究報告
- 電網(wǎng)行業(yè)工作匯報模板22
- 2024年度跨境電商平臺承包經(jīng)營合同3篇
- 2025年上半年人民日報社招聘應(yīng)屆高校畢業(yè)生85人筆試重點(diǎn)基礎(chǔ)提升(共500題)附帶答案詳解
- 山東省臨沂市2023-2024學(xué)年高二上學(xué)期期末考試生物試題 含答案
- 2024-2025學(xué)年一年級數(shù)學(xué)上冊期末樂考非紙筆測試題(二 )(蘇教版2024秋)
- 辦公樓電氣改造施工方案
- 2024秋期國家開放大學(xué)??啤陡叩葦?shù)學(xué)基礎(chǔ)》一平臺在線形考(形考任務(wù)一至四)試題及答案
- 2024-2024年江蘇省普通高中學(xué)業(yè)水平測試物理試卷(含答案)
- 行車起重作業(yè)風(fēng)險分析及管控措施
評論
0/150
提交評論