




版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
第七講進(jìn)程的同步Background背景TheCritical-SectionProblem臨界區(qū)的問(wèn)題SynchronizationHardware同步硬件Semaphores信號(hào)量ClassicalProblemsofSynchronization同步的經(jīng)典問(wèn)題CriticalRegions臨界區(qū)Monitors管城SynchronizationinSolaris2&Windows2000Solaris2和Windows2000的同步問(wèn)題OperatingSystemConceptsBackgroundConcurrentaccesstoshareddatamayresultindatainconsistency.對(duì)共享數(shù)據(jù)區(qū)的訪(fǎng)問(wèn)導(dǎo)致數(shù)據(jù)的不一致性Maintainingdataconsistencyrequiresmechanismstoensuretheorderlyexecutionofcooperatingprocesses.維持?jǐn)?shù)據(jù)的一致性要求保證合作進(jìn)程按一定的順序執(zhí)行的機(jī)制。Shared-memorysolutiontobounded-bufferproblem(Chapter4)allowsatmostn–1itemsinbufferatthesametime.Asolution,whereallNbuffersareusedisnotsimple.有限緩沖區(qū)問(wèn)題的共享存儲(chǔ)器解決方案一次在緩沖區(qū)中只容許n-1個(gè)項(xiàng)目,Supposethatwemodifytheproducer-consumercodebyaddingavariablecounter,initializedto0andincrementedeachtimeanewitemisaddedtothebufferOperatingSystemConceptsBounded-BufferShareddata
#defineBUFFER_SIZE10typedefstruct{ ...}item;itembuffer[BUFFER_SIZE];intin=0;intout=0;intcounter=0;OperatingSystemConceptsBounded-BufferProducerprocess
itemnextProduced;
while(1){ while(counter==BUFFER_SIZE) ;/*donothing*/ buffer[in]=nextProduced; in=(in+1)%BUFFER_SIZE; counter++; }OperatingSystemConceptsBounded-BufferConsumerprocess
itemnextConsumed;
while(1){ while(counter==0) ;/*donothing*/ nextConsumed=buffer[out]; out=(out+1)%BUFFER_SIZE; counter--; }
OperatingSystemConceptsBoundedBufferThestatements
counter++;
counter--;
mustbeperformedatomically.Atomicoperationmeansanoperationthatcompletesinitsentiretywithoutinterruption.
OperatingSystemConceptsBoundedBufferThestatement“count++”maybeimplementedinmachinelanguageas:
register1=counter register1=register1+1
counter=register1
Thestatement“count—”maybeimplementedas:
register2=counter
register2=register2–1
counter=register2OperatingSystemConceptsBoundedBufferIfboththeproducerandconsumerattempttoupdatethebufferconcurrently,theassemblylanguagestatementsmaygetinterleaved.Interleavingdependsuponhowtheproducerandconsumerprocessesarescheduled.OperatingSystemConceptsBoundedBufferAssumecounterisinitially5.Oneinterleavingofstatementsis:
producer:register1=counter(register1=5)
producer:register1=register1+1(register1=6)
consumer:register2=counter(register2=5)
consumer:register2=register2–1(register2=4)
producer:counter=register1(counter=6)
consumer:counter=register2(counter=4)
Thevalueofcountmaybeeither4or6,wherethecorrectresultshouldbe5.OperatingSystemConceptsRaceCondition
競(jìng)爭(zhēng)條件Racecondition:Thesituationwhereseveralprocessesaccess–andmanipulateshareddataconcurrently.Thefinalvalueoftheshareddatadependsuponwhichprocessfinisheslast.
競(jìng)爭(zhēng)條件:幾個(gè)進(jìn)程并行地訪(fǎng)問(wèn)和操作共享數(shù)據(jù)的情形。最后的結(jié)果取決于最后那一個(gè)進(jìn)程最后完成。Topreventraceconditions,concurrentprocessesmustbesynchronized.為了阻止出現(xiàn)競(jìng)爭(zhēng)的條件,并行進(jìn)程必須同步。OperatingSystemConceptsTheCritical-SectionProblem
臨界區(qū)問(wèn)題nprocessesallcompetingtousesomeshareddatan個(gè)進(jìn)程都需要競(jìng)爭(zhēng)使用某些共享的數(shù)據(jù)區(qū)。Eachprocesshasacodesegment,calledcriticalsection,inwhichtheshareddataisaccessed.
每個(gè)進(jìn)程有一個(gè)代碼段,稱(chēng)為臨界區(qū),訪(fǎng)問(wèn)共享數(shù)據(jù)的代碼都在臨界區(qū)中。Problem–ensurethatwhenoneprocessisexecutinginitscriticalsection,nootherprocessisallowedtoexecuteinitscriticalsection.問(wèn)題-確保當(dāng)一個(gè)進(jìn)程在臨界區(qū)中時(shí),沒(méi)有其它進(jìn)程在臨界區(qū)中。OperatingSystemConceptsSolutiontoCritical-SectionProblem
臨界區(qū)問(wèn)題的解決方案1. MutualExclusion(互斥條件):IfprocessPiisexecutinginitscriticalsection,thennootherprocessescanbeexecutingintheircriticalsections.2. Progress(進(jìn)入條件):Ifnoprocessisexecutinginitscriticalsectionandthereexistsomeprocessesthatwishtoentertheircriticalsection,thentheselectionoftheprocessesthatwillenterthecriticalsectionnextcannotbepostponedindefinitely.3. BoundedWaiting(有限等待的條件):Aboundmustexistonthenumberoftimesthatotherprocessesareallowedtoentertheircriticalsectionsafteraprocesshasmadearequesttoenteritscriticalsectionandbeforethatrequestisgranted.AssumethateachprocessexecutesatanonzerospeedNoassumptionconcerningrelativespeedofthenprocesses.OperatingSystemConceptsInitialAttemptstoSolveProblem
解決臨界區(qū)問(wèn)題的初步方案Only2processes,P0andP1僅考慮兩個(gè)進(jìn)程的情形GeneralstructureofprocessPi
(otherprocessPj)
進(jìn)程中的一般結(jié)構(gòu)
do{
entrysection criticalsection
exitsection remindersection }while(1);Processesmaysharesomecommonvariablestosynchronizetheiractions.進(jìn)程通過(guò)共享一些變量來(lái)同步它們的行為。OperatingSystemConceptsAlgorithm1Sharedvariables:intturn;
initiallyturn=0turn-i
PicanenteritscriticalsectionProcessPi
do{
while(turn!=i); criticalsection
turn=j; remindersection }while(1);Satisfiesmutualexclusion,butnotprogressOperatingSystemConceptsAlgorithm2Sharedvariablesbooleanflag[2];
initiallyflag[0]=flag[1]=false.flag[i]=true
PireadytoenteritscriticalsectionProcessPi
do{ flag[i]:=true;
while(flag[j]); criticalsection flag[i]=false;
remaindersection }while(1);Satisfiesmutualexclusion,butnotprogressrequirement.OperatingSystemConceptsAlgorithm3Combinedsharedvariablesofalgorithms1and2.ProcessPi
do{
flag[i]:=true;
turn=j;
while(flag[j]andturn=j); criticalsection
flag[i]=false; remaindersection }while(1);Meetsallthreerequirements;solvesthecritical-sectionproblemfortwoprocesses.OperatingSystemConceptsBakeryAlgorithm
面包師算法Beforeenteringitscriticalsection,processreceivesanumber.Holderofthesmallestnumberentersthecriticalsection.進(jìn)入臨界區(qū)前,進(jìn)程得到一個(gè)數(shù)字,持有最小數(shù)字的進(jìn)程獲準(zhǔn)進(jìn)入臨界區(qū)。IfprocessesPiandPjreceivethesamenumber,ifi<j,thenPiisservedfirst;elsePjisservedfirst.如果兩個(gè)進(jìn)程得到相同的數(shù)字,進(jìn)程號(hào)較小者獲準(zhǔn)進(jìn)入臨界區(qū)Thenumberingschemealwaysgeneratesnumbersinincreasingorderofenumeration;i.e.,1,2,3,3,3,3,4,5...永遠(yuǎn)以增序的形式產(chǎn)生數(shù)字。Criticalsectionfornprocessesn個(gè)進(jìn)程的臨界區(qū)算法OperatingSystemConceptsBakeryAlgorithm
面包師算法Notation<lexicographicalorder(ticket#,processid#)(a,b)<c,d)ifa<corifa=candb<dmax(a0,…,an-1)isanumber,k,suchthatk
aifori:0,
…,n–1Shareddata
booleanchoosing[n]; intnumber[n];Datastructuresareinitializedtofalseand0respectivelyOperatingSystemConceptsBakeryAlgorithmdo{
choosing[i]=true; number[i]=max(number[0],number[1],…,number[n–1])+1; choosing[i]=false;
for(j=0;j<n;j++){ while(choosing[j]); while((number[j]!=0)&&(number[j,j]<number[i,i])); } criticalsection
number[i]=0; remaindersection}while(1);OperatingSystemConceptsSynchronizationHardwareTestandmodifythecontentofawordatomically
.
booleanTestAndSet(boolean&target){ booleanrv=target; tqrget=true; returnrv; }OperatingSystemConceptsMutualExclusionwithTest-and-SetShareddata:
booleanlock=false;
ProcessPi
do{ while(TestAndSet(lock));
criticalsection lock=false;
remaindersection }OperatingSystemConceptsSynchronizationHardwareAtomicallyswaptwovariables.
voidSwap(boolean&a,boolean&b){ booleantemp=a; a=b; b=temp; }OperatingSystemConceptsMutualExclusionwithSwapShareddata(initializedtofalse):
booleanlock; booleanwaiting[n];
ProcessPi
do{ key=true; while(key==true) Swap(lock,key);
criticalsection lock=false;
remaindersection }OperatingSystemConceptsSemaphoresSynchronizationtoolthatdoesnotrequirebusywaiting.SemaphoreS–integervariablecanonlybeaccessedviatwoindivisible(atomic)operations
wait(S):
whileS0dono-op;
S--;
signal(S):
S++;OperatingSystemConceptsCriticalSectionofnProcessesShareddata: semaphoremutex;//initiallymutex=1
ProcessPi:
do{
wait(mutex);
criticalsection signal(mutex);
remaindersection
}while(1);
OperatingSystemConceptsSemaphoreImplementationDefineasemaphoreasarecord
typedefstruct{ intvalue;
structprocess*L;
}semaphore;
Assumetwosimpleoperations:blocksuspendstheprocessthatinvokesit.wakeup(P)resumestheexecutionofablockedprocessP.OperatingSystemConceptsImplementationSemaphoreoperationsnowdefinedas
wait(S):
S.value--; if(S.value<0){
addthisprocesstoS.L;
block; }
signal(S):
S.value++; if(S.value<=0){
removeaprocessPfromS.L;
wakeup(P); }OperatingSystemConceptsSemaphoreasaGeneralSynchronizationToolExecuteBinPjonlyafterAexecutedinPiUsesemaphoreflaginitializedto0Code: Pi Pj
A
wait(flag)
signal(flag) BOperatingSystemConceptsDeadlockandStarvationDeadlock–twoormoreprocessesarewaitingindefinitelyforaneventthatcanbecausedbyonlyoneofthewaitingprocesses.LetSandQbetwosemaphoresinitializedto1
P0
P1
wait(S); wait(Q);
wait(Q); wait(S);
signal(S); signal(Q);
signal(Q) signal(S);Starvation
–indefiniteblocking.Aprocessmayneverberemovedfromthesemaphorequeueinwhichitissuspended.OperatingSystemConceptsTwoTypesofSemaphoresCountingsemaphore–integervaluecanrangeoveranunrestricteddomain.Binarysemaphore–integervaluecanrangeonlybetween0and1;canbesimplertoimplement.CanimplementacountingsemaphoreSasabinarysemaphore.OperatingSystemConceptsImplementingSasaBinarySemaphoreDatastructures: binary-semaphoreS1,S2; intC:Initialization:
S1=1 S2=0 C=initialvalueofsemaphoreSOperatingSystemConceptsImplementingSwaitoperation
wait(S1); C--; if(C<0){ signal(S1); wait(S2); } signal(S1);
signaloperation
wait(S1); C++; if(C<=0) signal(S2); else signal(S1);OperatingSystemConceptsClassicalProblemsofSynchronizationBounded-BufferProblem
ReadersandWritersProblem
Dining-PhilosophersProblemOperatingSystemConceptsBounded-BufferProblemShareddata
semaphorefull,empty,mutex;
Initially:
full=0,empty=n,mutex=1OperatingSystemConceptsBounded-BufferProblemProducerProcess
do{ …
produceaniteminnextp … wait(empty); wait(mutex); …
addnextptobuffer … signal(mutex); signal(full); }while(1);
OperatingSystemConceptsBounded-BufferProblemConsumerProcess
do{ wait(full) wait(mutex); …
removeanitemfrombuffertonextc … signal(mutex); signal(empty); …
consumetheiteminnextc … }while(1);OperatingSystemConceptsReaders-WritersProblemShareddata
semaphoremutex,wrt;
Initially
mutex=1,wrt=1,readcount=0
OperatingSystemConceptsReaders-WritersProblemWriterProcess
wait(wrt); …
writingisperformed … signal(wrt);OperatingSystemConceptsReaders-WritersProblemReaderProcess
wait(mutex); readcount++; if(readcount==1) wait(rt); signal(mutex);
… readingisperformed …
wait(mutex); readcount--; if(readcount==0) signal(wrt); signal(mutex):OperatingSystemConceptsDining-PhilosophersProblemShareddata
semaphorechopstick[5];Initiallyallvaluesare1OperatingSystemConceptsDining-PhilosophersProblemPhilosopheri:
do{ wait(chopstick[i]) wait(chopstick[(i+1)%5]) …
eat … signal(chopstick[i]); signal(chopstick[(i+1)%5]); …
think … }while(1);OperatingSystemConceptsCriticalRegionsHigh-levelsynchronizationconstructAsharedvariablevoftypeT,isdeclaredas:
v:
shared
TVariablevaccessedonlyinsidestatement
region
v
when
B
do
S
whereBisabooleanexpression.
WhilestatementSisbeingexecuted,nootherprocesscanaccessvariablev.OperatingSystemConceptsCriticalRegionsRegionsreferringtothesamesharedvariableexcludeeachotherintime.
Whenaprocesstriestoexecutetheregionstatement,theBooleanexpressionBisevaluated.IfBistrue,statementSisexecuted.Ifitisfalse,theprocessisdelayeduntilBbecomestrueandnootherprocessisintheregionassociatedwithv.OperatingSystemConceptsExample–BoundedBufferShareddata:
structbuffer{ intpool[n]; intcount,in,out; }
OperatingSystemConceptsBoundedBufferProducerProcessProducerprocessinsertsnextpintothesharedbuffer
regionbufferwhen(count<n){
pool[in]=nextp;
in:=(in+1)%n;
count++;
}OperatingSystemConceptsBoundedBufferConsumerProcessConsumerprocessremovesanitemfromthesharedbufferandputsitinnextc
regionbufferwhen(count>0){ nextc=pool[out];
out=(out+1)%n;
count--;
}OperatingSystemConceptsImplementationregionxwhenBdoSAssociatewiththesharedvariablex,thefollowingvariables:
semaphoremutex,first-delay,second-delay;
intfirst-count,second-count;
Mutuallyexclusiveaccesstothecriticalsectionisprovidedbymutex.
IfaprocesscannotenterthecriticalsectionbecausetheBooleanexpressionBisfalse,itinitiallywaitsonthefirst-delaysemaphore;movedtothesecond-delaysemaphorebeforeitisallowedtoreevaluateB.OperatingSystemConceptsImplementationKeeptrackofthenumberofprocesseswaitingonfirst-delayandsecond-delay,withfirst-countandsecond-countrespectively.
ThealgorithmassumesaFIFOorderinginthequeuingofprocessesforasemaphore.
Foranarbitraryqueuingdiscipline,amorecomplicatedimplementationisrequired.OperatingSystemConceptsMonitorsHigh-levelsynchronizationconstructthatallowsthesafesharingofanabstractdatatypeamongconcurrentprocesses.
monitormonitor-name
{ sharedvariabledeclarations
procedurebody
P1
(…){ ... }
procedure
body
P2(…){ ... }
procedurebody
Pn
(…){ ... }
{ initializationcode
} }OperatingSystemConceptsMonitorsToallowaprocesstowaitwithinthemonitor,aconditionvariablemustbedeclared,as
conditionx,y;Conditionvariablecanonlybeusedwiththeoperationswaitandsignal.Theoperation
x.wait();
meansthattheprocessinvokingthisoperationissuspendeduntilanotherprocessinvokes
x.signal();Thex.signaloperationresumesexactlyonesuspendedprocess.Ifnoprocessissuspended,thenthesignaloperationhasnoeffect. OperatingSystemConceptsSchematicViewofaMonitorOperatingSystemConceptsMonitorWithConditionVariablesOperatingSystemConceptsDiningPhilosophersExample
monitordp { enum{thinking,hungry,eating}state[5]; conditionself[5]; voidpickup(inti) //followingslides voidputdown(inti) //followingslides voidtest(inti) //followingslides voidinit(){ for(inti=0;i<5;i++) state[i]=thinking; } }OperatingSystemConceptsDiningPhilosophers
voidpickup(inti){ state[i]=hungry; test[i]; if(state[i]!=eating) self[i].wait(); } voidputdown(inti){ state[i]=thinking; //testleftandrightneighbors test((i+4)%5); test((i+1)%5); }OperatingSystemConceptsDiningPhilosophers
voidtest(inti){ if((state[(I+4)%5]!=eating)&& (state[i]==hungry)&& (state[(i+1)%5]!=eating)){ state[i]=eating; self[i].signal(); } }
OperatingSystemConceptsMonitorImplementationUsingSemaphoresVariables
semaphoremutex;//(initially=1) semaphorenext;//(initially=0) intnext-count=0;
EachexternalprocedureFwillbereplacedby
wait(mutex); … bodyofF; …
if(next-count>0) signal(next) else signal(mutex);
Mutualexclusionwithinamonitorisensured.OperatingSystemConceptsMonitorImplementationForeachconditionvariablex,wehave:
semaphorex-sem;//(initially=0) intx-count=0;
Theoperationx.waitcanbeimple
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 安全生產(chǎn)檢查表及緊急處理方案
- 2025年脫硝催化劑項(xiàng)目申請(qǐng)報(bào)告
- 精神文化產(chǎn)品推廣承諾書(shū)7篇范文
- 2025湖南湘西自治州事業(yè)單位(醫(yī)衛(wèi)類(lèi))引進(jìn)高層次急需緊缺人才考試考前自測(cè)高頻考點(diǎn)模擬試題及答案詳解一套
- 企業(yè)內(nèi)訓(xùn)課程設(shè)計(jì)框架技能提升培訓(xùn)版
- 員工培訓(xùn)計(jì)劃制定模板全面版
- 讀紅樓夢(mèng)人物賞析作文6篇
- 2025湖北恩施州立強(qiáng)學(xué)校選聘副校長(zhǎng)、教師8人模擬試卷及1套參考答案詳解
- 讀魯濱遜漂流記后的勇敢探索讀后感(8篇)
- 經(jīng)營(yíng)權(quán)轉(zhuǎn)讓合同-經(jīng)營(yíng)權(quán)轉(zhuǎn)讓合同模板5篇
- 輸電線(xiàn)路水泥桿加固防腐施工方案
- 新版醫(yī)療器械管理制度零售單體藥店
- 小學(xué)教師專(zhuān)業(yè)發(fā)展 教學(xué)大綱
- 學(xué)校裝飾裝修工程施工方案
- 煙草證 申請(qǐng)書(shū)
- 屋面光伏工程施工組織設(shè)計(jì)
- 山體公園施工方案
- DL-T 5876-2024 水工瀝青混凝土應(yīng)用酸性骨料技術(shù)規(guī)范
- 膽囊癌完整版本
- 【MOOC】數(shù)據(jù)庫(kù)原理及應(yīng)用-電子科技大學(xué) 中國(guó)大學(xué)慕課MOOC答案
- 節(jié)約集約建設(shè)用地標(biāo)準(zhǔn) DG-TJ08-2422-2023
評(píng)論
0/150
提交評(píng)論