版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
CS162
OperatingSystemsand
SystemsProgramming
Lecture3
ConcurrencyandThreadDispatchingSeptember11,2013AnthonyD.JosephandJohnCanny/~cs162GoalsforTodayReview:ProcessesandThreadsThreadDispatchingCooperatingThreadsConcurrencyexamplesNote:Someslidesand/orpicturesinthefollowingareadaptedfromslides?2005Silberschatz,Galvin,andGagne.SlidescourtesyofAnthonyD.Joseph,JohnKubiatowicz,AJShankar,GeorgeNecula,AlexAiken,EricBrewer,RasBodik,IonStoica,DougTygar,andDavidWagner.WhyProcesses&Threads?Multiprogramming:RunmultipleapplicationsconcurrentlyProtection:Don’twantabadapplicationtocrashsystem!Goals:Process:unitofexecutionandallocationVirtualMachineabstraction:giveprocessillusionitownsmachine(i.e.,CPU,Memory,andIOdevicemultiplexing)Solution:Processcreation&switchingexpensiveNeedconcurrencywithinsameapp(e.g.,webserver)Challenge:Thread:DecoupleallocationandexecutionRunmultiplethreadswithinsameprocessSolution:Puttingittogether:ProcessMemoryI/OState(e.g.,file,socketcontexts)CPUstate(PC,SP,registers..)SequentialstreamofinstructionsA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);…(Unix)ProcessResourcesStackStoredinOSPuttingittogether:Processes…Process1Process2ProcessNCPUsched.OSCPU(1core)1processatatimeCPUstateIOstateMem.CPUstateIOstateMem.CPUstateIOstateMem.Switchoverhead:highCPUstate:lowMemory/IOstate:highProcesscreation:highProtectionCPU:yesMemory/IO:yesSharingoverhead:high(involvesatleastacontextswitch)Puttingittogether:ThreadsProcess1CPUsched.OSCPU(1core)1threadatatimeIOstateMem.…threadsProcessNIOstateMem.…threads…Switchoverhead:low
(onlyCPUstate)Threadcreation:lowProtectionCPU:yesMemory/IO:NoSharingoverhead:low(threadswitchoverheadlow)CPUstateCPUstateCPUstateCPUstatePuttingittogether:Multi-CoresProcess1CPUsched.OSIOstateMem.…threadsProcessNIOstateMem.…threads…Switchoverhead:low
(onlyCPUstate)Threadcreation:lowProtectionCPU:yesMemory/IO:NoSharingoverhead:low(threadswitchoverheadlow)core1Core2Core3Core4CPU4threadsatatimeCPUstateCPUstateCPUstateCPUstatePuttingittogether:Hyper-ThreadingProcess1CPUsched.OSIOstateMem.…threadsProcessNIOstateMem.…threads…Switchoverheadbetweenhardware-threads:very-low
(doneinhardware)ContentionforALUs/FPUsmayhurtperformancecore1CPUcore2core3core48threadsatatimehardware-threads(hyperthreading)CPUstateCPUstateCPUstateCPUstateClassificationRealoperatingsystemshaveeitherOneormanyaddressspacesOneormanythreadsperaddressspaceMach,OS/2,LinuxWinNTto8,Solaris,HP-UX,OSXEmbeddedsystems(Geoworks,VxWorks,JavaOS,etc)JavaOS,Pilot(PC)TraditionalUNIXMS/DOS,earlyMacintoshManyOne#threadsperAS:ManyOne#ofaddrspaces:ThreadStateStatesharedbyallthreadsinprocess/addrspaceContentofmemory(globalvariables,heap)I/Ostate(filesystem,networkconnections,etc)State“private”toeachthreadKeptinTCBThreadControlBlockCPUregisters(including,programcounter)Executionstack–whatisthis?ExecutionStackParameters,temporaryvariablesReturnPCsarekeptwhilecalledproceduresareexecutingReview:ExecutionStackExampleStackholdsfunctionarguments,returnaddressPermitsrecursiveexecutionCrucialtomodernlanguagesA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;addrX:addrY:addrU:addrV:addrZ:............Review:ExecutionStackExampleStackholdsfunctionarguments,returnaddressPermitsrecursiveexecutionCrucialtomodernlanguagesA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;StackPointerStackGrowthA:tmp=1ret=addrZaddrX:addrY:addrU:addrV:addrZ:............Review:ExecutionStackExampleStackholdsfunctionarguments,returnaddressPermitsrecursiveexecutionCrucialtomodernlanguagesA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;StackPointerStackGrowthA:tmp=1ret=addrZaddrX:addrY:addrU:addrV:addrZ:............Review:ExecutionStackExampleStackholdsfunctionarguments,returnaddressPermitsrecursiveexecutionCrucialtomodernlanguagesA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;StackPointerStackGrowthA:tmp=1ret=addrZaddrX:addrY:addrU:addrV:addrZ:............Review:ExecutionStackExampleStackholdsfunctionarguments,returnaddressPermitsrecursiveexecutionCrucialtomodernlanguagesA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;StackPointerStackGrowthA:tmp=1ret=addrZB:ret=addrYaddrX:addrY:addrU:addrV:addrZ:............Review:ExecutionStackExampleStackholdsfunctionarguments,returnaddressPermitsrecursiveexecutionCrucialtomodernlanguagesA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;StackPointerStackGrowthA:tmp=1ret=addrZB:ret=addrYaddrX:addrY:addrU:addrV:addrZ:............Review:ExecutionStackExampleStackholdsfunctionarguments,returnaddressPermitsrecursiveexecutionCrucialtomodernlanguagesA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;StackPointerStackGrowthA:tmp=1ret=addrZB:ret=addrYC:ret=addrUaddrX:addrY:addrU:addrV:addrZ:............Review:ExecutionStackExampleStackholdsfunctionarguments,returnaddressPermitsrecursiveexecutionCrucialtomodernlanguagesA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;StackPointerStackGrowthA:tmp=1ret=addrZB:ret=addrYC:ret=addrUaddrX:addrY:addrU:addrV:addrZ:............Review:ExecutionStackExampleStackholdsfunctionarguments,returnaddressPermitsrecursiveexecutionCrucialtomodernlanguagesA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;A:tmp=2ret=addrVStackPointerStackGrowthA:tmp=1ret=addrZB:ret=addrYC:ret=addrUaddrX:addrY:addrU:addrV:addrZ:............Review:ExecutionStackExampleStackholdsfunctionarguments,returnaddressPermitsrecursiveexecutionCrucialtomodernlanguagesA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;A:tmp=2ret=addrVStackPointerStackGrowthA:tmp=1ret=addrZB:ret=addrYC:ret=addrUaddrX:addrY:addrU:addrV:addrZ:............Review:ExecutionStackExampleA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;A:tmp=2ret=addrVStackPointerStackGrowthA:tmp=1ret=addrZB:ret=addrYC:ret=addrUaddrX:addrY:addrU:addrV:addrZ:............Output:2Review:ExecutionStackExampleA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;StackPointerStackGrowthA:tmp=1ret=addrZB:ret=addrYC:ret=addrUaddrX:addrY:addrU:addrV:addrZ:............Output:2Review:ExecutionStackExampleA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;StackPointerStackGrowthA:tmp=1ret=addrZB:ret=addrYaddrX:addrY:addrU:addrV:addrZ:............Output:2Review:ExecutionStackExampleA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;StackPointerStackGrowthA:tmp=1ret=addrZaddrX:addrY:addrU:addrV:addrZ:............Output:21Review:ExecutionStackExampleA(inttmp){if(tmp<2)B();printf(tmp);}B(){C();}C(){A(2);}A(1);exit;addrX:addrY:addrU:addrV:addrZ:............Output:21Single-ThreadedExampleImaginethefollowingCprogram:
main(){ ComputePI(“pi.txt”); PrintClassList(“clist.text”); }Whatisthebehaviorhere?ProgramwouldneverprintoutclasslistWhy?ComputePIwouldneverfinishUseofThreadsVersionofprogramwithThreads:
main(){ CreateThread(ComputePI(“pi.txt”)); CreateThread(PrintClassList(“clist.text”)); }Whatdoes“CreateThread”do?StartindependentthreadrunninggivenprocedureWhatisthebehaviorhere?Now,youwouldactuallyseetheclasslistThisshouldbehaveasiftherearetwoseparateCPUsCPU1CPU2CPU1CPU2TimeCPU1CPU2MemoryFootprintofTwo-ThreadExampleIfwestoppedthisprogramandexamineditwithadebugger,wewouldseeTwosetsofCPUregistersTwosetsofStacksQuestions:Howdowepositionstacksrelativeto
eachother?Whatmaximumsizeshouldwechoose
forthestacks?Whathappensifthreadsviolatethis?Howmightyoucatchviolations?CodeGlobalDataHeapStack1Stack2AddressSpacePerThreadStateEachThreadhasaThreadControlBlock(TCB)ExecutionState:CPUregisters,programcounter(PC),pointertostack(SP)Schedulinginfo:state,priority,CPUtimeVariousPointers(forimplementingschedulingqueues)Pointertoenclosingprocess(PCB)Etc(addstuffasyoufindaneed)OSKeepstrackofTCBsinprotectedmemoryInArray,orLinkedList,or…LifecycleofaThread(orProcess)Asathreadexecutes,itchangesstate:new:Thethreadisbeingcreatedready:Thethreadiswaitingtorunrunning:Instructionsarebeingexecutedwaiting:Threadwaitingforsomeeventtooccurterminated:Thethreadhasfinishedexecution“Active”threadsarerepresentedbytheirTCBsTCBsorganizedintoqueuesbasedontheirstateReadyQueueAndVariousI/ODeviceQueuesThreadnotrunningTCBisinsomeschedulerqueueSeparatequeueforeachdevice/signal/conditionEachqueuecanhaveadifferentschedulerpolicyOtherStateTCB9LinkRegistersOtherStateTCB6LinkRegistersOtherStateTCB16LinkRegistersOtherStateTCB8LinkRegistersOtherStateTCB2LinkRegistersOtherStateTCB3LinkRegistersHeadTailHeadTailHeadTailHeadTailHeadTailReadyQueueSSDUnit0DiskUnit0DiskUnit2EtherNetwk0Administrivia:ProjectSignupProjectSignup:Use“Group/SectionSignup”Link4-5memberstoagroup,everyonemustattendthesamesectionUsePiazzapinnedteammatesearchthread(pleaseclosewhendone!)Onlysubmitoncepergroup!DueThu(1/31)by11:59PMEveryoneingroupmusthaveloggedintotheircs162-xxaccountsoncebeforeyouregisterthegroup,Selectatleast3potentialsectionsNewsectionassignments:Watch“Group/SectionAssignment”LinkAttendnewsectionsNEXTweekSectionTimeLocationTA101Tu10:00A-11:00A6EvansDavid102Tu11:00A-12:00P75EvansDavid103Tu1:00P-2:00P75EvansNeeraja104Tu3:00P-4:00P2070VLSBDaniel105Tu11:00A-12:00P3105EtcheverryDaniel106Tu1:00P-2:00P385LeConteWesley107Tu2:00P-3:00P71EvansNeeraja108Tu6:00P-7:00P71EvansWesleyAdministrivia:ProjectSignupProjectSignup:Use“Group/SectionSignup”Link4-5memberstoagroup,everyonemustattendthesamesectionUsePiazzapinnedteammatesearchthread(pleaseclosewhendone!)Onlysubmitoncepergroup!DueThu(9/12)by11:59PMEveryoneingroupmusthaveloggedintotheircs162-xxaccountsoncebeforeyouregisterthegroup,Selectatleast3potentialsectionsNewsectionassignments:Watch“Group/SectionAssignment”LinkAttendnewsectionsNEXTweekSectionTimeLocationTA101Tu9:00A-10:00A310SodaMatt102Tu10:00A-11:00A75EvansMatt103Tu11:00A-12:00P71EvansGeorge104Tu3:00P-4:00P24WheelerGeorge105We10:00A-11:00A85EvansKevin106We11:00A-12:00P85EvansKevin107TBATBATBA108TBATBATBA5minBreakDispatchLoopConceptually,thedispatchingloopoftheoperatingsystemlooksasfollows:
Loop{ RunThread(); ChooseNextThread(); SaveStateOfCPU(curTCB); LoadStateOfCPU(newTCB); }ThisisaninfiniteloopOnecouldarguethatthisisallthattheOSdoesRunningathreadConsiderfirstportion:RunThread()HowdoIrunathread?Loaditsstate(registers,stackpointer)intoCPULoadenvironment(virtualmemoryspace,etc)JumptothePCHowdoesthedispatchergetcontrolback?Internalevents:threadreturnscontrolvoluntarilyExternalevents:threadgetspreemptedYieldingthroughInternalEventsBlockingonI/OTheactofrequestingI/OimplicitlyyieldstheCPUWaitingona“signal”fromotherthreadThreadaskstowaitandthusyieldstheCPUThreadexecutesayield()ThreadvolunteerstogiveupCPU computePI(){while(TRUE){ComputeNextDigit();yield();}}Notethatyield()mustbecalledbyprogrammerfrequentlyenough!Review:StackforYieldingThreadHowdowerunanewthread?
run_new_thread(){ newThread=PickNewThread(); switch(curThread,newThread); ThreadHouseKeeping();/*deallocatesfinishedthreads*/ }Finishedthreadnotkilledrightaway.Why?Movethemin“exit/terminated”stateThreadHouseKeeping()deallocatesfinishedthreadsyieldComputePIStackgrowthrun_new_threadkernel_yieldTraptoOSswitchReview:StackforYieldingThreadHowdowerunanewthread?
run_new_thread(){ newThread=PickNewThread(); switch(curThread,newThread); ThreadHouseKeeping();/*deallocatesfinishedthreads*/ }Howdoesdispatcherswitchtoanewthread?Saveanythingnextthreadmaytrash:PC,regs,SPMaintainisolationforeachthreadyieldComputePIStackgrowthrun_new_threadkernel_yieldTraptoOSswitchReview:TwoThreadYieldExampleConsiderthefollowingcodeblocks:
procA(){ B(); } procB(){ while(TRUE){ yield(); } }Supposewehavetwothreads:ThreadsSandTThreadSStackgrowthAB(while)yieldrun_new_threadswitchkernel_yieldThreadTAB(while)yieldrun_new_threadswitchkernel_yieldDetour:InterruptControllerInterruptsinvokedwithinterruptlinesfromdevicesInterruptcontrollerchoosesinterruptrequesttohonorMaskenables/disablesinterruptsPriorityencoderpickshighestenabledinterruptSoftwareInterruptSet/ClearedbySoftwareInterruptidentityspecifiedwithIDlineCPUcandisableallinterruptswithinternalflagNon-maskableinterruptline(NMI)can’tbedisabledNetworkIntIDInterruptInterruptMaskControlSoftwareInterruptNMICPUPriorityEncoderTimerIntDisableReview:PreemptiveMultithreadingUsethetimerinterrupttoforceschedulingdecisionsTimerInterruptroutine:
TimerInterrupt(){
DoPeriodicHouseKeeping();
run_new_thread();
}Thisisoftencalledpreemptivemultithreading,sincethreadsarepreemptedforbetterschedulingSolvesproblemofuserwhodoesn’tinsertyield();SomeRoutinerun_new_threadTimerInterruptInterruptswitchStackgrowthWhyallowcooperatingthreads?Peoplecooperate;computershelp/enhancepeople’slives,socomputersmustcooperateByanalogy,thenon-reproducibility/non-determinismofpeopleisanotableproblemfor“carefullylaidplans”Advantage1:ShareresourcesOnecomputer,manyusersOnebankbalance,manyATMsWhatifATMswereonlyupdatedatnight?Embeddedsystems(robotcontrol:coordinatearm&hand)Advantage2:SpeedupOverlapI/OandcomputationMultiprocessors–chopupprogramintoparallelpiecesAdvantage3:ModularityChoplargeproblemupintosimplerpiecesTocompile,forinstance,gcccallscpp|cc1|cc2|as|ldMakessystemeasiertoextendThreadedWebServerMultithreadedversion:serverLoop(){ connection=AcceptCon(); ThreadCreate(ServiceWebPage(),connection); }Advantagesofthreadedversion:Cansharefilecacheskeptinmemory,resultsofCGIscripts,otherthingsThreadsaremuchcheapertocreatethanprocesses,sothishasalowerper-requestoverheadWhatiftoomanyrequestscomeinatonce?ThreadPoolsProblemwithpreviousversion:UnboundedThreadsWhenweb-sitebecomestoopopular–throughputsinksInstead,allocateabounded“pool”ofthreads,representingthemaximumlevelofmultiprogramming
master(){
allocThreads(slave,queue);
while(TRUE){
con=AcceptCon();
Enqueue(queue,con);
wakeUp(queue);
}
}slave(queue){
while(TRUE){
con=Dequeue(queue);
if(con==null)
sleepOn(queue);
else
ServiceWebPage(con);
}
}MasterThreadThreadPoolqueueATMBankServerATMserverproblem:ServiceasetofrequestsDosowithoutcorruptingdatabaseDon’thandouttoomuchmoneyATMbankserverexampleSupposewewantedtoimplementaserverprocesstohandlerequestsfromanATMnetwork:
BankServer(){
while(TRUE){
ReceiveRequest(&op,&acctId,&amount);
ProcessRequest(op,acctId,amount);
}
} ProcessRequest(op,acctId,amount){
if(op==deposit)Deposit(acctId,amount);
elseif…
} Deposit(acctId,amount){
acct=GetAccount(acctId);/*mayusediskI/O*/
acct->balance+=amount;
StoreAccount(acct);/*InvolvesdiskI/O*/
}Howcouldwespeedthisup?MorethanonerequestbeingprocessedatonceMultiplethreads(multi-proc,oroverlapcompandI/O)CanThreadsHelp?Onethreadperrequest!Requestsproceedstocompletion,blockingasrequired:
Deposit(acctId,amount){
acct=GetAccount(actId); /*MayusediskI/O*/
acct->balance+=amount;
StoreAccount(acct); /*InvolvesdiskI/O*/
}Unfortunately,sharedstatecangetcorrupted:
Thread1
Thread2
loadr1,acct->balance
loadr1,acct->balance
addr1,amount2
storer1,acct->balance
addr1,amount1
storer1,acct->balance
Problemisatthe
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年度港口碼頭船舶引航與拖輪服務(wù)合同4篇
- 二零二五版教育設(shè)施工程監(jiān)理服務(wù)合同示范文本2篇
- 二零二五年度道路橋梁監(jiān)理委托合同范本2篇
- 二零二五年度紅酒銷售代理融資租賃合同2篇
- 二零二五年度第五章第五節(jié)合同標(biāo)的擔(dān)保與信用評(píng)估及違約責(zé)任合同3篇
- 二零二五年度智能穿戴產(chǎn)品股份收購合同
- 二零二五年度充電樁場地租賃與智能監(jiān)控系統(tǒng)合同
- 專業(yè)私教健身指導(dǎo)合同:2024工作室版版B版
- 二零二五年度甲乙丙方公寓轉(zhuǎn)租租賃合同
- 二零二五年度電視節(jié)目特邀嘉賓演出合同
- 深圳2024-2025學(xué)年度四年級(jí)第一學(xué)期期末數(shù)學(xué)試題
- 中考語文復(fù)習(xí)說話要得體
- 《工商業(yè)儲(chǔ)能柜技術(shù)規(guī)范》
- 華中師范大學(xué)教育技術(shù)學(xué)碩士研究生培養(yǎng)方案
- 醫(yī)院醫(yī)學(xué)倫理委員會(huì)章程
- 初中班主任案例分析4篇
- 公司7s管理組織實(shí)施方案
- Q∕GDW 12147-2021 電網(wǎng)智能業(yè)務(wù)終端接入規(guī)范
- 仁愛英語單詞默寫本(全六冊(cè))英譯漢
- 公園廣場綠地文化設(shè)施維修改造工程施工部署及進(jìn)度計(jì)劃
- 塑料件缺陷匯總
評(píng)論
0/150
提交評(píng)論