计算机线程 外文翻译 外文文献 英文文献.docx
《计算机线程 外文翻译 外文文献 英文文献.docx》由会员分享,可在线阅读,更多相关《计算机线程 外文翻译 外文文献 英文文献.docx(10页珍藏版)》请在冰豆网上搜索。
![计算机线程 外文翻译 外文文献 英文文献.docx](https://file1.bdocx.com/fileroot1/2023-1/6/3337088d-491c-400e-a17a-62347ced8bda/3337088d-491c-400e-a17a-62347ced8bda1.gif)
计算机线程外文翻译外文文献英文文献
译文
Chapter25ThreadBasics
WhyDoesWindowsSupportThreads?
...………………………………………….…..…691
ThreadOverhead…..…………………………………………………………………….…...692
StoptheMadness…………..………………………………………………………….……...696
CPUTrends……………………………………………………………………….…..….……699
NUMAArchitectureMachines…..……………………………….………………….……..700
CLRThreadsandWindowsThreads………………………………..……………….…….703
UsingaDedicatedThreadtoPerformanAsynchronous
Compute-BoundOperation…………………………………………………………….……704
ReasonstoUseThreads……..……………………………………………...…………….….706
ThreadSchedulingandPriorities……………….……………………..……………….…...708
ForegroundThreadsversusBackgroundThreads………………………………………..713
WhatNow?
................................................................................................................................715
Inthischapter,Iintroducethebasicconceptsconcerningthreads,andIofferawayfordeveloperstoconceptualizeaboutthemandtheiruse.I’llexplainwhyMicrosoftWindowsintroducedtheconceptofthreads,CPUtrends,therelationshipbetweencommonlanguageruntime(CLR)threadsandWindowsthreads,theoverheadassociatedwithusingthreads,howWindowsschedulesthreads,theMicrosoft.NETFrameworkclassesthatexposethreadproperties,andmuchmore.
ThechaptersinPartVofthisbook,“Threading,”explainhowWindowsandtheCLRworktogethertoprovideathreadingarchitecture.Itismyhopethatafterreadingthesechapters,youwilltakeawayafoundationofknowledgethatwillallowyoutoeffectivelyusethreadstodesignandbuildresponsive,reliable,andscalableapplicationsandcomponents.
WhyDoesWindowsSupportThreads?
Backintheearlydaysofcomputers,operatingsystemsdidn’toffertheconceptofathread.Ineffect,therewasjustonethreadofexecutionthatranthroughouttheentiresystem,whichincludedbothoperatingsystemcodeandapplicationcode.Theproblemwithhavingonlyonethreadofexecutionwasthatalong-runningtaskwouldpreventothertasksfromexecuting.
Forexample,inthedaysof16-bitWindows,itwasverycommonforanapplicationthatwasprintingadocumenttostalltheentiremachine,causingtheOSandallotherapplicationstostopresponding.
And,sometimesapplicationswouldhaveabuginthem,resultinginaninfiniteloopthatalsostoppedtheentiremachinefromoperating.Atthispoint,theenduserwouldhavenochoicebuttorebootthecomputerbypressingtheresetbuttonorpowerswitch.Ofcourse,endusershateddoingthis(theystilldo,infact)becauseallrunningapplicationsterminated;moreimportantly,anydatathattheseapplicationswereprocessingwasthrownoutofmemoryandlost.Microsoftknewthat16-bitWindowswouldnotbeagoodenoughoperatingsystemtokeepMicrosoftrelevant
asthecomputerindustryprogressed,sotheysetouttobuildanewOStoaddresstheneedsofcorporationsandindividuals.ThisnewOShadtoberobust,reliable,scalable,andsecure,andithadtoimprovethemanydeficienciesof16-bitWindows.ThisOSkerneloriginallyshippedinMicrosoftWindowsNT.Overtheyears,thiskernelhashadmanytweaksandfeaturesaddedtoit.ThelatestversionofthiskernelshipsinthelatestversionsoftheMicrosoftclientandserverWindowsoperatingsystems.
WhenMicrosoftwasdesigningthisOSkernel,theydecidedtoruneachinstanceofanapplicationinwhatiscalledaprocess.Aprocessisjustacollectionofresourcesthatisusedbyasingleinstanceofanapplication.Eachprocessisgivenavirtualaddressspace,ensuringthatthecodeanddatausedbyoneprocessisnotaccessibletoanotherprocess.Thismakesapplicationinstancesrobustbecauseoneprocesscannotcorruptcodeordatabeingusedbyanother.Inaddition,theOS’skernelcodeanddataarenotaccessibletoprocesses;therefore,it’snotpossibleforapplicationcodetocorruptoperatingsystemcodeordata.Sonow,applicationcodecannotcorruptotherapplicationsortheOSitself,andthewholecomputingexperienceismuchbetterforendusers.Inaddition,thesystemismoresecurebecauseapplicationcodecannotaccessusernames,passwords,creditcardinformation,orothersensitiveinformationthatisinusebyanotherapplicationortheoperatingsystemitself.
Thisisallwellandgood,butwhatabouttheCPUitself?
Whatifanapplicationentersaninfiniteloop?
Well,ifthereisonlyoneCPUinthemachine,thenitexecutestheinfiniteloopandcannotexecuteanythingelse,sowhilethedatacannotbecorruptedandismoresecure,thesystemcouldstillstoprespondingtotheenduser.Microsoftneededtofixthisproblem,too,andthreadsweretheanswer.AthreadisaWindowsconceptwhosejobistovirtualizetheCPU.Windowsgiveseachprocessitsveryownthread(whichfunctionssimilartoaCPU),andifapplicationcodeentersaninfiniteloop,theprocessassociatedwiththatcodefreezesup,butotherprocesses(whichhavetheirownthreads)arenotfrozen;theykeeprunning!
ThreadOverhead
ThreadsareawesomebecausetheyenableWindowstoberesponsiveevenwhenapplicationsareexecutinglong-runningtasks.Also,threadsallowtheusertouseoneapplication(likeTaskManager)toforciblykillanapplicationthatappearsfrozenbecauseitisexecutingalong-runningtask.Butaswitheveryvirtualizationmechanism,threadshavespace(memoryconsumption)andtime(runtimeexecutionperformance)overheadassociatedwiththem.Let’sexplorethisoverheadinmoredetailnow.Everythreadhasoneofeachofthefollowing:
●ThreadkernelobjectTheOSallocatesandinitializesoneofthesedatastructuresforeachthreadcreatedinthesystem.Thedatastructurecontainsabunchofproperties(discussedlaterinthischapter)thatdescribethethread.Thisdatastructurealsocontainswhatiscalledthethread’scontext.ThecontextisablockofmemorythatcontainsasetoftheCPU’sregisters.WhenWindowsisrunningonamachinewithanx86CPU,thethread’scontextusesabout700bytesofmemory.Forx64andIA64CPUs,thecontextisabout1,240and2,500bytesofmemory,respectively.
●Threadenvironmentblock(TEB)TheTEBisablockofmemoryallocatedandinitializedinusermode(addressspacethatapplicationcodecanquicklyaccess).TheTEBconsumes1pageofmemory(4KBonx86andx64CPUs,8KBonanIA64CPU).TheTEBcontainstheheadofthethread’sexception-handlingchain.Eachtryblockthatthethreadentersinsertsanodeintheheadofthischain;thenodeisremovedfromthechainwhenthethreadexistsinthetryblock.Inaddition,theTEBcontainsthethread’sthread-localstoragedataaswellassomedatastructuresforusebyGraphicsDeviceInterface(GDI)andOpenGLgraphics.
●User-modestackTheuser-modestackisusedforlocalvariablesandargumentspassedtomethods.Italsocontainstheaddressindicatingwhatthethreadshouldexecutenextwhenthecurrentmethodreturns.Bydefault,Windowsallocates1MBofmemoryforeachthread’suser-modestack.
●Kernel-modestackThekernel-modestackisalsousedwhenapplicationcodepassesargumentstoakernel-modefunctionintheoperatingsystem.Forsecurityreasons,Windowscopiesanyargumentspassedfromuser-modecodetothekernelfromthethread’suser-modestacktothethread’skernel-modestack.Oncecopied,thekernelcanverifythearguments’values,andsincetheapplicationcodecan’taccessthekernelmodestack,theapplicationcan’tmodifythearguments’valuesaftertheyhavebeenvalidatedandtheOSkernelcodebeginstooperateonthem.Inaddition,thekernelcallsmethodswithinitselfandusesthekernel-modestacktopassitsownarguments,tostoreafunction’slocalvariables,andtostorereturnaddresses.Thekernel-modestackis12KBwhenrunningona32-bitWindowssystemand24KBwhenrunningona64-bitWindowssystem.
●DLLthread-attachandthread-detachnotificationsWindowshasapolicythatwheneverathreadiscreatedinaprocess,allDLLsloadedinthatprocesshavetheirDllMainmethodcalled,passingaDLL_THREAD_ATTACHflag.Similarly,wheneverathreaddies,allDLLsintheprocesshavetheirDllMainmethodcalled,passingitaDLL_THREAD_DETACHflag.SomeDLLsneedthesenotificationstoperformsomespecialinitializationorcleanupforeachthreadcreated/destroyedintheprocess.Forexample,theC-RuntimelibraryDLLallocatessomethread-localstoragestatethatisrequiredshouldthethreadusefunctionscontainedwithintheC-Runtimelibrary.
IntheearlydaysofWindows,manyprocesseshadmaybe5or6DLLsloadedintothem,buttoday,someprocesseshaveseveralhundredDLLsloadedintothem.Rightnow,onmymachine,MicrosoftOfficeOutlookhasabout250DLLsloadedintoitsprocessaddressspace!
ThismeansthatwheneveranewthreadiscreatedinOfficeOutlook,250DLLfunctionsmustgetcalledbeforethethreadisallowedtodowhatitwascreatedtodo.Andthese250functionsmustbecalledagainwheneverathreadinOutlookdies.Wow—thiscanseriouslyaffecttheperformanceofcreatinganddestroyingthreadswithinaprocess.
Sonow,youseeallthespaceandtimeoverheadthatisassociatedwithcreatingathread,lettingitsitaroundinthesystem,anddestroyingit.Butthesituationgetsevenworse—nowwe’regoingtostarttalkingaboutcontextswitching.AcomputerwithonlyoneCPUinitcandoonlyonethingatatime.Therefore,WindowshastosharetheactualCPUhardwareamongallthethreads(logicalCPUs)thataresittingaroundinthesystem.
Atanygivenmomentintime,WindowsassignsonethreadtoaCPU.Thatthreadisallowedtorunforatime-slice(sometimesreferredtoasaquantum).Whenthetime-sliceexpires,Windowscontextswitchestoanotherthread.EverycontextswitchrequiresthatWindowsperformsthef