版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 护理护理计划制定
- 部编版二年级语文下册《羿射九日 第1课时》
- 护理护理职业素养
- 护理科研课题申报的科研平台建设
- 理赔专员的客户服务能力提升策略
- 基于情感计算的智能座舱开发实践分享
- 旅游行业客服面试技巧要点
- 基于虚拟现实技术的教育培训应用探索
- 基于激光雷达的无人机飞行控制技术研究报告
- 智能制造赋能城镇产业园区更新方案
- 儿童画手工葡萄课件
- DL∕T 5768-2018 电网技术改造工程工程量清单计算规范
- T-CPIA 0056-2024 漂浮式水上光伏发电锚固系统设计规范
- 20S121生活热水加热机组(热水机组选用与安装)
- (高清版)DZT 0388-2021 矿区地下水监测规范
- 环卫公司清扫保洁范围及清扫方案
- 《护理疑难病例讨论》课件
- GB/T 12758-2023城市轨道交通信号系统通用技术条件
- 高速公路安全养护作业规程优质资料
- 雁行理论优质获奖课件
- 伊利亚穆辛俄国指挥艺术的一代宗师
评论
0/150
提交评论