35
CSE 3320 Operating Systems Deadlock Jia Rao Department of Computer Science and Engineering http://ranger.uta.edu/~jrao

CSE 3320 Operating Systems Deadlock - CSE SERVICES

  • Upload
    others

  • View
    10

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CSE 3320 Operating Systems Deadlock - CSE SERVICES

CSE3320OperatingSystems

Deadlock

Jia RaoDepartmentofComputerScience and Engineering

http://ranger.uta.edu/~jrao

Page 2: CSE 3320 Operating Systems Deadlock - CSE SERVICES

RecapoftheLastClass• Raceconditions• Mutualexclusionandcriticalregions• Twosimpleapproaches

o DisablinginterruptandLockvariables

• Busywaitingo Strictalternation,Peterson’sandTSL

• Semaphores• Mutexes• Monitors• MessagePassing• Barrier

Page 3: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DeadlockDefinitions• Twoormoreprocesseseachblockedandwaitingforresourcesthey

willnevergetwithoutdrasticactionso Somethingpreemptsaresourceo Aprocessiskilled

• Asetofprocessesisdeadlockedifeachprocessinthesetiswaitingforaneventthatonlyanotherprocessinthesetcancause,thus,noprocesscano run

o releaseresources

o beawakened

Page 4: CSE 3320 Operating Systems Deadlock - CSE SERVICES

ResourcesandDeadlocks(1)• Examplesofcomputerresources

o printers

o tapedrives

o tables

o software

• Processesneedaccesstoresourcesinareasonableorder

• SupposeaprocessholdsresourceAandrequestsresourceBo atthesametimeanotherprocessholdsBandrequestsA

o bothareblockedandremainso,deadlocks

Bothprocesseswanttohaveexclusiveaccess toAandB!

Page 5: CSE 3320 Operating Systems Deadlock - CSE SERVICES

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!

Page 6: CSE 3320 Operating Systems Deadlock - CSE SERVICES

ResourcesandDeadlocks(3)• Sequenceofeventsrequiredtousearesource

o requesttheresource

o usetheresource

o releasetheresource

• Mustwaitifrequestisdeniedo requestingprocessmaybeblocked

o mayfailwitherrorcode

Page 7: CSE 3320 Operating Systems Deadlock - CSE SERVICES

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!

Page 8: CSE 3320 Operating Systems Deadlock - CSE SERVICES

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?

Page 9: CSE 3320 Operating Systems Deadlock - CSE SERVICES

FourConditionsforDeadlockCoffman(1971)1.Mutualexclusioncondition

l eachresourceassignedto1processorisavailable2.Holdandwaitcondition

l processholdingresourcescanrequestadditional3.Nopreemptioncondition

l previouslygrantedresourcescannotbeforciblytakenaway

4.Circularwaitconditionl mustbeacircularchainof2ormoreprocessesl eachiswaitingforresourcesheldbynextmemberofthe

chain

Page 10: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DeadlockModeling(1)• Modeledwithdirectedgraphs

o Acyclemeansadeadlockinvolvingtheprocessesandresources

o resourceRassignedtoprocessAo processBisrequesting/waitingforresourceSo processCandDareindeadlockoverresourcesTandU

Page 11: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DeadlockModeling(2)(a) – (c)Sequential modelno deadlock, no parallelism

WhatiftheOSknewtheimpendingdeadlockofgrantingBresourceSatstep(f)?

Page 12: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DeadlockModeling(3)

HowdeadlockcanbeavoidedbyOS’ re-ordering

(o) (p) (q)

Page 13: CSE 3320 Operating Systems Deadlock - CSE SERVICES

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

Page 14: CSE 3320 Operating Systems Deadlock - CSE SERVICES

TheOstrichAlgorithm• Pretendthereisnoproblem

• Reasonableifo deadlocksoccurveryrarely

o costofpreventionishigh

• UNIXandWindowstakethisapproach

• Itisatradeoffbetweeno convenience

o correctness

Page 15: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DetectionwithOneResourceType• Assumption:onlyoneresourceofeachtypeexists

• Notetheresourceownershipandrequests• Acyclecanbefoundwithinthegraph,denotingdeadlock

AholdsRandwantsS……

Page 16: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DetectaCycleinaGraph° Adatastructuretofindifagraphisatreethatiscycle-free

• depth-firstsearching(P.445)• Left-right,top-to-bottom:R,A,B,C,S,D,T,E,F

Page 17: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DetectionwithMultipleResourcesofEachType(1)° Deadlockdetectionalgorithm:

• Twovectorsandtwomatrixes• Vectorcomparison;A≤BmeansAi≤Bifor1≤i ≤m• Observation:Sum_Cij +Aj =Ej

Datastructuresneededbydeadlockdetectionalgorithm

Page 18: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DetectionwithMultipleResourcesofEachType(2)° Key:acompletedprocesscanreleaseitsresourcessoasto

giveotherprocesseschancestoacquireresourcesandrun• LookforaprocessPi,IfR[i]≤A?ifso,A=R[i]+C[i]

Whatifprocess2needsaCD-ROMdriveand2tapedriversandtheplotter?

Anexampleforthedeadlockdetectionalgorithm

Whentorunthedeadlockdetectionalgorithm?WhyCPUutilization?

P1P2p3

Althoughthealgorithmisnondeterministic,theresultisalwaysthesameTheschedulingorderdonotmatter

Page 19: CSE 3320 Operating Systems Deadlock - CSE SERVICES

RecoveryfromDeadlock• Recoverythroughpreemption

o takearesourcefromsomeotherprocesso dependsonthenatureoftheresource

• Recoverythroughrollbacko checkpoint aprocessperiodically,resultingasequenceofcheckpointfileso usethissavedstateo restarttheprocessifitisfounddeadlockedo Processesindatabaseandnetworkapplicationsarenoteasytorollback,why?

• Recoverythroughkillingprocesseso crudestbutsimplestwaytobreakadeadlocko killoneoftheprocessesinthedeadlockcycleo theotherprocessesgetitsresourceso chooseprocessthatcanbererunfromthebeginning,noteasy!

Willkillingaprocessnotinthedeadlockcyclehelp?

Page 20: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DeadlockAvoidance° Allocateresourceswiselytoavoiddeadlocks

• Butcertaininformationshouldbeavailableinadvance• Base:conceptofsafestates

Two process resource trajectories.

Wherestatet cangotoavoiddeadlock?

WhatiftisattheintersectionofI1andI5?

Whichareaisunsafe?

Page 21: CSE 3320 Operating Systems Deadlock - CSE SERVICES

(a) (b) (c) (d) (e)

SafeStates(w/oneresourcetype)° Safestate

• ifitisnotdeadlocked,and,thereissome schedulingorderinwhicheveryprocesscanruntocompletionevenifallofthemrequesttheirmaximumnumberofresourcesimmediately

Whystate(a)issafe?

Page 22: CSE 3320 Operating Systems Deadlock - CSE SERVICES

UnsafeStates(w/oneresourcetype)° Unsafestate

• thereisnoguarantee ofhavingsomeschedulingorderinwhicheveryprocesscanruntocompletionevenifallofthemrequesttheirmaximumnumberofresourcesimmediately

• Notthesameasadeadlockedstate,why?Whatisthedifference?

(a)(b)(c)(d)

Whystate(b)isNOT safe?

Page 23: CSE 3320 Operating Systems Deadlock - CSE SERVICES

TheBanker'sAlgorithmforaSingleResource° Thealgorithmmodelsonthewayofabankermightdealwithagroupof

customerstowhomhehasgrantedlinesofcredit

• Notallcustomersneedtheirmaximumcreditlinesimultaneously

• Toseeifastateissafe,thebankercheckstoseeifhehasenoughresourcestosatisfysomecustomer

Threeresourceallocationstates:(a)safe;(b)safe;(c)unsafe

(a)(b)(c)

Page 24: CSE 3320 Operating Systems Deadlock - CSE SERVICES

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

Page 25: CSE 3320 Operating Systems Deadlock - CSE SERVICES

TheBanker'sAlgorithmforMultipleResources(2)

AfterprocessBwasgrantedascanner,nowprocessEwantsthelastscanner,canitbegranted?Why?

Whyinpracticethealgorithmisessentiallyuseless?

Page 26: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DeadlockPrevention(1)AttackthemutualexclusionconditionofCoffmanRules• Somedevices(suchasprinter)canbespooled

o onlytheprinterdaemonusesprinterresourceo thusdeadlockforprintereliminatedo Butthediskcouldbedeadlocked,thoughmoreunlikely

• Notalldevicescanbespooled,e.g.,processtable• Principle:

o avoidassigningresourcewhennotabsolutelynecessaryo asfewprocessesaspossibleactuallyclaimtheresource

Page 27: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DeadlockPrevention(2)AttacktheHold-and-WaitconditionofCoffmanRules• Requireprocessestorequestallresourcesbeforestarting

o aprocessneverhastowaitforwhatitneeds• Problems

o maynotknowrequiredresourcesatstartofruno alsotiesupresourcesotherprocessescouldbeusing

} Lessconcurrency!• Variation:

o processmusttemporarilygiveupallresourceso thenrequestallimmediatelyneeded

Page 28: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DeadlockPrevention(3)AttacktheNo-PreemptionConditionofCoffmanRules

• Thisisnotaviableoption

• Consideraprocessgiventheprintero halfwaythroughitsjob

o nowforciblytakeawayprinter

o !!??

Page 29: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DeadlockPrevention(4)AttacktheCircularWaitConditionofCoffmanRules

° Aprocessisentitledonlytoasingleresourceatanymoment° Provideaglobalnumberingofalltheresources

• Aprocesscanrequestresourceswhenevertheywantto,butallrequestsmustbemadeinnumericalorder(ornoprocessrequestsaresourcelowerthanwhatitisalreadyholding)

(a)Normallyorderedresources(b)aresourcegraph

• Whynodeadlock?

• Isitfeasibleinimplementation?– whatisagoodordering?

Page 30: CSE 3320 Operating Systems Deadlock - CSE SERVICES

DeadlockPreventionSummary

Summaryofapproachestodeadlockprevention

Whatisthedifferencebetweendeadlockavoidanceanddeadlockprevention?

dynamicschedulingvs.staticruling

Page 31: CSE 3320 Operating Systems Deadlock - CSE SERVICES

Two-PhaseLocking• PhaseOne

o processtriestolockallrecordsitneeds,oneatatimeo ifneededrecordfoundlocked,startovero (norealworkdoneinphaseone)

• Ifphaseonesucceeds,itstartssecondphase,o performingupdateso releasinglocks

• Notesimilaritytorequestingallresourcesatonceo Attackingthehold-and-waitcondition

• Algorithmworkswhereprogrammercanarrangeo programcanbestoppedandrestartedinthefirstphase,insteadof

blocking!

Page 32: CSE 3320 Operating Systems Deadlock - CSE SERVICES

Non-resourceDeadlocks• Possiblefortwoprocessestodeadlock

o eachiswaitingfortheothertodosometask

• Canhappenwithsemaphoreso eachprocessrequiredtodoadown() ontwosemaphores(mutex and

another)

o ifdoneinwrongorder,deadlockresults

Page 33: CSE 3320 Operating Systems Deadlock - CSE SERVICES

Re:TheProducer-consumerProblemw/Semaphores

UC.ColoradoSprings

whatifthetwodownsintheproducer’scodewerereversedinorder,somutex wasdecrementedbeforeemptyinsteadofafterit?

Page 34: CSE 3320 Operating Systems Deadlock - CSE SERVICES

Starvation• Algorithmtoallocatearesource

o maybetogivetoshortestjobfirsto worksgreatformultipleshortjobsinasystem

• Itmaycauselongjobstobepostponedindefinitelyo eventhoughnotblockedo Strictprioritymaygivetrouble!

• Solution:o First-come,first-serveresourceallocationpolicy

Whatisthekeydifferencebetweendeadlockandstarvation?

Page 35: CSE 3320 Operating Systems Deadlock - CSE SERVICES

Summary• Deadlocksanditsmodeling

• Deadlockdetection

• Deadlockrecovery

• Deadlockavoidanceo Resourcetrajectories

o Safeandunsafestates

o Thebanker’salgorithm

• Two-phaselocking