cse 3320 operating systems deadlock - cse services
TRANSCRIPT
CSE3320OperatingSystems
Deadlock
Jia RaoDepartmentofComputerScience and Engineering
http://ranger.uta.edu/~jrao
RecapoftheLastClass• Raceconditions• Mutualexclusionandcriticalregions• Twosimpleapproaches
o DisablinginterruptandLockvariables
• Busywaitingo Strictalternation,Peterson’sandTSL
• Semaphores• Mutexes• Monitors• MessagePassing• Barrier
DeadlockDefinitions• Twoormoreprocesseseachblockedandwaitingforresourcesthey
willnevergetwithoutdrasticactionso Somethingpreemptsaresourceo Aprocessiskilled
• Asetofprocessesisdeadlockedifeachprocessinthesetiswaitingforaneventthatonlyanotherprocessinthesetcancause,thus,noprocesscano run
o releaseresources
o beawakened
ResourcesandDeadlocks(1)• Examplesofcomputerresources
o printers
o tapedrives
o tables
o software
• Processesneedaccesstoresourcesinareasonableorder
• SupposeaprocessholdsresourceAandrequestsresourceBo atthesametimeanotherprocessholdsBandrequestsA
o bothareblockedandremainso,deadlocks
Bothprocesseswanttohaveexclusiveaccess toAandB!
ResourcesandDeadlocks(2)• Deadlocksoccurwhen…
o processesaregrantedexclusiveaccess tohardware,e.g.,I/Odevices
o processesaregrantedexclusiveaccess tosoftware,e.g.,databaserecords
o werefertothesegenerallyasresources
• Pre-emptibleresourceso canbetakenawayfromaprocesswithnoilleffects,e.g.,Mem
• Non-preemptible resourceso willcausetheprocesstofailiftakenaway,e.g.,CDburner
Ingeneral,deadlocksinvolve non-preemptible and exclusive resources!
ResourcesandDeadlocks(3)• Sequenceofeventsrequiredtousearesource
o requesttheresource
o usetheresource
o releasetheresource
• Mustwaitifrequestisdeniedo requestingprocessmaybeblocked
o mayfailwitherrorcode
ResourceAcquisition
• Canusingsemaphoresavoiddeadlocks?typedef int semaphore; typedef int semaphore;semaphoreresource_1; semaphoreresource_1;
semaphoreresource_2;
voidprocess_A (void){ voidprocess_A (void){down(&resource_1); down(&resource_1);use_resource_1(); down(&resource_2);up(&resource_1); use_both_resources();
} up(&resource_2);up(&resource_1);
}
Usingsemaphoretoprotectresources.(a)Oneresource.(b)Tworesources.Butusingsemaphoreswisely!
ResourceAcquisition(2)typedef int semaphore; typedef int semaphore;semaphoreresource_1; semaphoreresource_1;semaphoreresource_2; semaphoreresource_2;
voidprocess_A (void){ voidprocess_A (void){down(&resource_1); down(&resource_1);down(&resource_2); down(&resource_2);use_both_resources(); use_both_resources();up(&resource_2); up(&resource_2);up(&resource_1); up(&resource_1);
} }
voidprocess_B (void){ voidprocess_B (void){down(&resource_1); down(&resource_2);down(&resource_2); down(&resource_1);use_both_resources(); use_both_resources();up(&resource_2); up(&resource_1);up(&resource_1); up(&resource_2);
} }
(a)Deadlock-freecode. (b)Codewithapotentialdeadlock,why?
FourConditionsforDeadlockCoffman(1971)1.Mutualexclusioncondition
l eachresourceassignedto1processorisavailable2.Holdandwaitcondition
l processholdingresourcescanrequestadditional3.Nopreemptioncondition
l previouslygrantedresourcescannotbeforciblytakenaway
4.Circularwaitconditionl mustbeacircularchainof2ormoreprocessesl eachiswaitingforresourcesheldbynextmemberofthe
chain
DeadlockModeling(1)• Modeledwithdirectedgraphs
o Acyclemeansadeadlockinvolvingtheprocessesandresources
o resourceRassignedtoprocessAo processBisrequesting/waitingforresourceSo processCandDareindeadlockoverresourcesTandU
DeadlockModeling(2)(a) – (c)Sequential modelno deadlock, no parallelism
WhatiftheOSknewtheimpendingdeadlockofgrantingBresourceSatstep(f)?
DeadlockModeling(3)
HowdeadlockcanbeavoidedbyOS’ re-ordering
(o) (p) (q)
DealingwithDeadlocks• Strategies for dealing with Deadlocks
1. just ignore the problem altogether
2.detection and recovery
3.dynamic avoidance • careful resource allocation
4.prevention • negating one of the four necessary conditions
TheOstrichAlgorithm• Pretendthereisnoproblem
• Reasonableifo deadlocksoccurveryrarely
o costofpreventionishigh
• UNIXandWindowstakethisapproach
• Itisatradeoffbetweeno convenience
o correctness
DetectionwithOneResourceType• Assumption:onlyoneresourceofeachtypeexists
• Notetheresourceownershipandrequests• Acyclecanbefoundwithinthegraph,denotingdeadlock
AholdsRandwantsS……
DetectaCycleinaGraph° Adatastructuretofindifagraphisatreethatiscycle-free
• depth-firstsearching(P.445)• Left-right,top-to-bottom:R,A,B,C,S,D,T,E,F
DetectionwithMultipleResourcesofEachType(1)° Deadlockdetectionalgorithm:
• Twovectorsandtwomatrixes• Vectorcomparison;A≤BmeansAi≤Bifor1≤i ≤m• Observation:Sum_Cij +Aj =Ej
Datastructuresneededbydeadlockdetectionalgorithm
DetectionwithMultipleResourcesofEachType(2)° Key:acompletedprocesscanreleaseitsresourcessoasto
giveotherprocesseschancestoacquireresourcesandrun• LookforaprocessPi,IfR[i]≤A?ifso,A=R[i]+C[i]
Whatifprocess2needsaCD-ROMdriveand2tapedriversandtheplotter?
Anexampleforthedeadlockdetectionalgorithm
Whentorunthedeadlockdetectionalgorithm?WhyCPUutilization?
P1P2p3
Althoughthealgorithmisnondeterministic,theresultisalwaysthesameTheschedulingorderdonotmatter
RecoveryfromDeadlock• Recoverythroughpreemption
o takearesourcefromsomeotherprocesso dependsonthenatureoftheresource
• Recoverythroughrollbacko checkpoint aprocessperiodically,resultingasequenceofcheckpointfileso usethissavedstateo restarttheprocessifitisfounddeadlockedo Processesindatabaseandnetworkapplicationsarenoteasytorollback,why?
• Recoverythroughkillingprocesseso crudestbutsimplestwaytobreakadeadlocko killoneoftheprocessesinthedeadlockcycleo theotherprocessesgetitsresourceso chooseprocessthatcanbererunfromthebeginning,noteasy!
Willkillingaprocessnotinthedeadlockcyclehelp?
DeadlockAvoidance° Allocateresourceswiselytoavoiddeadlocks
• Butcertaininformationshouldbeavailableinadvance• Base:conceptofsafestates
Two process resource trajectories.
Wherestatet cangotoavoiddeadlock?
WhatiftisattheintersectionofI1andI5?
Whichareaisunsafe?
(a) (b) (c) (d) (e)
SafeStates(w/oneresourcetype)° Safestate
• ifitisnotdeadlocked,and,thereissome schedulingorderinwhicheveryprocesscanruntocompletionevenifallofthemrequesttheirmaximumnumberofresourcesimmediately
Whystate(a)issafe?
UnsafeStates(w/oneresourcetype)° Unsafestate
• thereisnoguarantee ofhavingsomeschedulingorderinwhicheveryprocesscanruntocompletionevenifallofthemrequesttheirmaximumnumberofresourcesimmediately
• Notthesameasadeadlockedstate,why?Whatisthedifference?
(a)(b)(c)(d)
Whystate(b)isNOT safe?
TheBanker'sAlgorithmforaSingleResource° Thealgorithmmodelsonthewayofabankermightdealwithagroupof
customerstowhomhehasgrantedlinesofcredit
• Notallcustomersneedtheirmaximumcreditlinesimultaneously
• Toseeifastateissafe,thebankercheckstoseeifhehasenoughresourcestosatisfysomecustomer
Threeresourceallocationstates:(a)safe;(b)safe;(c)unsafe
(a)(b)(c)
TheBanker'sAlgorithmforMultipleResources(1)
° ThealgorithmlooksforaprocessPi,IfR[i]≤A?ifso,A=R[i]+C[i]
• HowRisachieved?R=M(Maximum)- C
• Whatistheunderlyingassumption?Minfoavailableinadvance
IfprocessBrequestsascanner,canitbegranted?Why?
E=P+A
TheBanker'sAlgorithmforMultipleResources(2)
AfterprocessBwasgrantedascanner,nowprocessEwantsthelastscanner,canitbegranted?Why?
Whyinpracticethealgorithmisessentiallyuseless?
DeadlockPrevention(1)AttackthemutualexclusionconditionofCoffmanRules• Somedevices(suchasprinter)canbespooled
o onlytheprinterdaemonusesprinterresourceo thusdeadlockforprintereliminatedo Butthediskcouldbedeadlocked,thoughmoreunlikely
• Notalldevicescanbespooled,e.g.,processtable• Principle:
o avoidassigningresourcewhennotabsolutelynecessaryo asfewprocessesaspossibleactuallyclaimtheresource
DeadlockPrevention(2)AttacktheHold-and-WaitconditionofCoffmanRules• Requireprocessestorequestallresourcesbeforestarting
o aprocessneverhastowaitforwhatitneeds• Problems
o maynotknowrequiredresourcesatstartofruno alsotiesupresourcesotherprocessescouldbeusing
} Lessconcurrency!• Variation:
o processmusttemporarilygiveupallresourceso thenrequestallimmediatelyneeded
DeadlockPrevention(3)AttacktheNo-PreemptionConditionofCoffmanRules
• Thisisnotaviableoption
• Consideraprocessgiventheprintero halfwaythroughitsjob
o nowforciblytakeawayprinter
o !!??
DeadlockPrevention(4)AttacktheCircularWaitConditionofCoffmanRules
° Aprocessisentitledonlytoasingleresourceatanymoment° Provideaglobalnumberingofalltheresources
• Aprocesscanrequestresourceswhenevertheywantto,butallrequestsmustbemadeinnumericalorder(ornoprocessrequestsaresourcelowerthanwhatitisalreadyholding)
(a)Normallyorderedresources(b)aresourcegraph
• Whynodeadlock?
• Isitfeasibleinimplementation?– whatisagoodordering?
DeadlockPreventionSummary
Summaryofapproachestodeadlockprevention
Whatisthedifferencebetweendeadlockavoidanceanddeadlockprevention?
dynamicschedulingvs.staticruling
Two-PhaseLocking• PhaseOne
o processtriestolockallrecordsitneeds,oneatatimeo ifneededrecordfoundlocked,startovero (norealworkdoneinphaseone)
• Ifphaseonesucceeds,itstartssecondphase,o performingupdateso releasinglocks
• Notesimilaritytorequestingallresourcesatonceo Attackingthehold-and-waitcondition
• Algorithmworkswhereprogrammercanarrangeo programcanbestoppedandrestartedinthefirstphase,insteadof
blocking!
Non-resourceDeadlocks• Possiblefortwoprocessestodeadlock
o eachiswaitingfortheothertodosometask
• Canhappenwithsemaphoreso eachprocessrequiredtodoadown() ontwosemaphores(mutex and
another)
o ifdoneinwrongorder,deadlockresults
Re:TheProducer-consumerProblemw/Semaphores
UC.ColoradoSprings
whatifthetwodownsintheproducer’scodewerereversedinorder,somutex wasdecrementedbeforeemptyinsteadofafterit?
Starvation• Algorithmtoallocatearesource
o maybetogivetoshortestjobfirsto worksgreatformultipleshortjobsinasystem
• Itmaycauselongjobstobepostponedindefinitelyo eventhoughnotblockedo Strictprioritymaygivetrouble!
• Solution:o First-come,first-serveresourceallocationpolicy
Whatisthekeydifferencebetweendeadlockandstarvation?
Summary• Deadlocksanditsmodeling
• Deadlockdetection
• Deadlockrecovery
• Deadlockavoidanceo Resourcetrajectories
o Safeandunsafestates
o Thebanker’salgorithm
• Two-phaselocking