56
Operating System Operating System Concepts Concepts Ku-Yaw Chang Ku-Yaw Chang [email protected] [email protected] Assistant Professor, Department of Assistant Professor, Department of Computer Science and Information Engineering Computer Science and Information Engineering Da-Yeh University Da-Yeh University

Operating System Concepts

Embed Size (px)

DESCRIPTION

Operating System Concepts. Ku-Yaw Chang [email protected] Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University. Chapter 8 Deadlocks. In a multiprogramming environment Several processes may compete for a finite number of resources - PowerPoint PPT Presentation

Citation preview

Page 1: Operating System Concepts

Operating System Operating System ConceptsConcepts

Ku-Yaw ChangKu-Yaw [email protected]@mail.dyu.edu.tw

Assistant Professor, Department of Assistant Professor, Department of Computer Science and Information EngineeringComputer Science and Information Engineering

Da-Yeh UniversityDa-Yeh University

Page 2: Operating System Concepts

22Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Chapter 8 DeadlocksChapter 8 Deadlocks

In a multiprogramming environmentIn a multiprogramming environment Several processes may compete for a finite number of resourcesSeveral processes may compete for a finite number of resources

A process requests resourcesA process requests resources If no available, the process enter a If no available, the process enter a waitwait state. state. Waiting process may never again change stateWaiting process may never again change state

Such a situation is called a Such a situation is called a deadlockdeadlock

A law passed by the Kansas legislature A law passed by the Kansas legislature When two trains approach each other at a crossing, both shall When two trains approach each other at a crossing, both shall

come to a full stop and neither shall start up again until the other come to a full stop and neither shall start up again until the other has gone.has gone.

Page 3: Operating System Concepts

33Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Chapter 8 DeadlocksChapter 8 Deadlocks

1.1. System ModelSystem Model

2.2. Deadlock Deadlock CharacterizationCharacterization

3.3. Methods for Methods for Handling DeadlocksHandling Deadlocks

4.4. Deadlock PreventionDeadlock Prevention

5.5. Deadlock Avoidance Deadlock Avoidance

6.6. Deadlock DetectionDeadlock Detection

7.7. Recovery from Recovery from DeadlockDeadlock

8.8. SummarySummary

9.9. ExercisesExercises

Page 4: Operating System Concepts

44Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.1 System Model8.1 System Model

A process may utilize a resource in only the A process may utilize a resource in only the following sequencefollowing sequence RequestRequest

If this request cannot be granted immediately, the requesting If this request cannot be granted immediately, the requesting process must wait.process must wait.

UseUse ReleaseRelease

ExamplesExamples open and close file system callsopen and close file system calls allocate and free memory system callsallocate and free memory system calls

Page 5: Operating System Concepts

55Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Deadlock StateDeadlock State

A set of processes is in a deadlock state when A set of processes is in a deadlock state when every process in the set is waiting for an event every process in the set is waiting for an event that can be caused only by another process in that can be caused only by another process in the set.the set.ResourcesResources Physical resourcesPhysical resources

printers, tape drives, memory space, CPUprinters, tape drives, memory space, CPU Logical resourcesLogical resources

files, semaphores, monitorsfiles, semaphores, monitors Other types of eventsOther types of events

IPC facilitiesIPC facilities

Page 6: Operating System Concepts

66Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Deadlock ExamplesDeadlock Examples

Example Example System has 2 tape drives.System has 2 tape drives. PP11 and and PP22 each hold one tape drive and each each hold one tape drive and each

needs another one.needs another one.

Example Example semaphores semaphores AA and and B B, initialized to 1, initialized to 1

PP00 PP11

wait (A);wait (A); wait (B);wait (B);wait (B);wait (B); wait (A);wait (A);

Page 7: Operating System Concepts

77Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Bridge Crossing ExampleBridge Crossing Example

Traffic only in one direction.Traffic only in one direction.Each section of a bridge can be viewed as a Each section of a bridge can be viewed as a resource.resource.If a deadlock occurs, it can be resolved if one car If a deadlock occurs, it can be resolved if one car backs up (preempt resources and rollback).backs up (preempt resources and rollback).Several cars may have to be backed up if a Several cars may have to be backed up if a deadlock occurs.deadlock occurs.Starvation is possible.Starvation is possible.

Page 8: Operating System Concepts

88Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Chapter 8 DeadlocksChapter 8 Deadlocks

1.1. System ModelSystem Model

2.2. Deadlock Deadlock CharacterizationCharacterization

3.3. Methods for Methods for Handling DeadlocksHandling Deadlocks

4.4. Deadlock PreventionDeadlock Prevention

5.5. Deadlock Avoidance Deadlock Avoidance

6.6. Deadlock DetectionDeadlock Detection

7.7. Recovery from Recovery from DeadlockDeadlock

8.8. SummarySummary

9.9. ExercisesExercises

Page 9: Operating System Concepts

99Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.2.1 Necessary Conditions8.2.1 Necessary Conditions

A deadlock situation arise if the following four A deadlock situation arise if the following four conditions hold simultaneouslyconditions hold simultaneously Mutual exclusionMutual exclusion

At least one resource must be held in a nonsharable modeAt least one resource must be held in a nonsharable mode Hold and waitHold and wait

Hold at least one resource and wait to acquire additional Hold at least one resource and wait to acquire additional resources that are currently being held by other processesresources that are currently being held by other processes

No preemptionNo preemptionResources cannot be preemptedResources cannot be preempted

Circular waitCircular waitPP0 0 is waiting for a resource that is held by is waiting for a resource that is held by PP11, , PP11 is waiting for is waiting for a resource that is held by a resource that is held by PP22, …, , …, PPnn–1–1 is waiting for a resource is waiting for a resource that is held by that is held by PPnn, and , and PPnn is waiting for a resource that is held is waiting for a resource that is held by by PP00..

Page 10: Operating System Concepts

1010Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.2.2 Resource-Allocation Graph8.2.2 Resource-Allocation Graph

System resource-allocation graphSystem resource-allocation graph A directed graph for describing deadlocksA directed graph for describing deadlocks

A set of vertices VA set of vertices V Active processesActive processes

P = {PP = {P11, P, P22, …, P, …, Pnn}} Resource typesResource types

R = {RR = {R11, R, R22, …, R, …, Rnn}}

A set of edges EA set of edges E A request edgeA request edge

PPii -> R -> Rjj

An assignment edgeAn assignment edge

RRjj -> P -> Pii

Pi

Pi Rj

Rj

4 instances4 instances

Page 11: Operating System Concepts

1111Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Resource Allocation GraphResource Allocation Graph

Sets P, R, and ESets P, R, and E P = {PP = {P11, P, P22, P, P33}} R = {RR = {R11, R, R22, R, R3 3 , R, R44}} E = {PE = {P1 1 ->R->R11, P, P2 2 ->R->R33, ,

R R1 1 ->P->P22, R, R2 2 ->P->P22,, R R2 2 ->P->P11, R, R3 3 ->P->P3 3 }}

Resource instancesResource instances RR11 : one instance : one instance RR22 : two instances : two instances RR33 : one instance : one instance RR44 : three instances : three instances

Page 12: Operating System Concepts

1212Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Resource Allocation GraphResource Allocation Graph

If the graph contains no cyclesIf the graph contains no cycles No process in the system is deadlockedNo process in the system is deadlocked

If the graph does contain a cycleIf the graph does contain a cycle A deadlock may existA deadlock may exist

Page 13: Operating System Concepts

1313Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Resource Allocation GraphResource Allocation Graph

PP33 requests an instance of R requests an instance of R22

Two minimal cycles existTwo minimal cycles existPP11 -> R -> R1 1 -> P-> P22 -> R -> R3 3 -> ->

PP33 -> R -> R2 2 -> P-> P11

PP22 -> R -> R3 3 -> P-> P33 -> R -> R2 2 -> P-> P22

Processes PProcesses P11, P, P22, and P, and P33 are are

deadlockeddeadlocked

Page 14: Operating System Concepts

1414Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Resource Allocation GraphResource Allocation Graph

A cycle existsA cycle exists PP11 -> R -> R1 1 -> P-> P33 -> R -> R2 2 -> P-> P11

No deadlockNo deadlock PP44 may release its instance of R may release its instance of R22

That resource can the be allocated That resource can the be allocated to Pto P33, breaking the cycle, breaking the cycle

Page 15: Operating System Concepts

1515Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Deadlock CharacterizationDeadlock Characterization

In summary, if a resource-allocation graph In summary, if a resource-allocation graph Does not have a cycleDoes not have a cycle

The system is The system is notnot in a deadlock state in a deadlock state Have a cycleHave a cycle

The system The system maymay or or may notmay not be in a deadlock state be in a deadlock state

Page 16: Operating System Concepts

1616Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Chapter 8 DeadlocksChapter 8 Deadlocks

1.1. System ModelSystem Model

2.2. Deadlock Deadlock CharacterizationCharacterization

3.3. Methods for Methods for Handling DeadlocksHandling Deadlocks

4.4. Deadlock PreventionDeadlock Prevention

5.5. Deadlock Avoidance Deadlock Avoidance

6.6. Deadlock DetectionDeadlock Detection

7.7. Recovery from Recovery from DeadlockDeadlock

8.8. SummarySummary

9.9. ExercisesExercises

Page 17: Operating System Concepts

1717Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.3 Methods for Handling Deadlocks8.3 Methods for Handling Deadlocks

Deal with the deadlock problem in one of three Deal with the deadlock problem in one of three waysways Use a protocol to Use a protocol to preventprevent or or avoidavoid deadlocks, deadlocks,

ensuring that the system will never enter a deadlock ensuring that the system will never enter a deadlock statestate

Allow the system to enter a deadlock state, detect it, Allow the system to enter a deadlock state, detect it, and recover.and recover.

Ignore the problem altogether, and pretend that Ignore the problem altogether, and pretend that deadlocks never occur in the systemdeadlocks never occur in the system

Deadlocks occurs infrequently (say, once per year)Deadlocks occurs infrequently (say, once per year)

Page 18: Operating System Concepts

1818Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Chapter 8 DeadlocksChapter 8 Deadlocks

1.1. System ModelSystem Model

2.2. Deadlock Deadlock CharacterizationCharacterization

3.3. Methods for Methods for Handling DeadlocksHandling Deadlocks

4.4. Deadlock PreventionDeadlock Prevention

5.5. Deadlock Avoidance Deadlock Avoidance

6.6. Deadlock DetectionDeadlock Detection

7.7. Recovery from Recovery from DeadlockDeadlock

8.8. SummarySummary

9.9. ExercisesExercises

Page 19: Operating System Concepts

1919Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.4 Deadlock Prevention8.4 Deadlock Prevention

Ensure at least one of the four necessary Ensure at least one of the four necessary conditions cannot holdconditions cannot hold Mutual ExclusionMutual Exclusion Hold and WaitHold and Wait No PreemptionNo Preemption Circular WaitCircular Wait

Page 20: Operating System Concepts

2020Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Deadlock PreventionDeadlock Prevention

Mutual ExclusionMutual Exclusion Must hold for nonsharable resources ( ex. a printer)Must hold for nonsharable resources ( ex. a printer) We cannot prevent deadlocks by denying the mutual-We cannot prevent deadlocks by denying the mutual-

exclusion conditionexclusion conditionSome resources are intrinsically nonsharableSome resources are intrinsically nonsharable

Hold and WaitHold and Wait Whenever a process requests a resource, it does not Whenever a process requests a resource, it does not

hold any other resourceshold any other resourcesRequest and be allocated all resources before executionRequest and be allocated all resources before executionRequest resources only when the process has noneRequest resources only when the process has none

Main disadvantagesMain disadvantagesLow resource utilizationLow resource utilizationStarvation is possibleStarvation is possible

Page 21: Operating System Concepts

2121Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Deadlock PreventionDeadlock Prevention

No PreemptionNo Preemption If a process that is holding some resources requests another If a process that is holding some resources requests another

resource that cannot be immediately allocated to it, then all resource that cannot be immediately allocated to it, then all resources currently being held are released.resources currently being held are released.

Preempted resources are added to the list of resources for which Preempted resources are added to the list of resources for which the process is waiting.the process is waiting.

Process will be restarted only when it can regain its old Process will be restarted only when it can regain its old resources, as well as the new ones that it is requesting.resources, as well as the new ones that it is requesting.

Applied to resources whose state can be easily saved and Applied to resources whose state can be easily saved and restoredrestored

Such as CPU registers and memory spacesSuch as CPU registers and memory spaces

No applied to printers and tape drivesNo applied to printers and tape drives

Page 22: Operating System Concepts

2222Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Deadlock PreventionDeadlock Prevention

Circular WaitCircular Wait Impose a total ordering of all resource typesImpose a total ordering of all resource types

A one-to-one function A one-to-one function FF: : RR -> -> NN NN is the set of natural numbers is the set of natural numbers

require that each process requests resources in an require that each process requests resources in an increasing order of enumerationincreasing order of enumeration

Initially request any number of instances of a resource type Initially request any number of instances of a resource type RRii

Request instances of resource type Request instances of resource type RRjj if and only if if and only if FF((RRjj)>)>FF((RRii)) ExampleExample

FF(tape drive) = 1(tape drive) = 1FF(disk drive) = 5(disk drive) = 5FF(printer) = 12(printer) = 12

Page 23: Operating System Concepts

2323Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Chapter 8 DeadlocksChapter 8 Deadlocks

1.1. System ModelSystem Model

2.2. Deadlock Deadlock CharacterizationCharacterization

3.3. Methods for Methods for Handling DeadlocksHandling Deadlocks

4.4. Deadlock PreventionDeadlock Prevention

5.5. Deadlock AvoidanceDeadlock Avoidance

6.6. Deadlock DetectionDeadlock Detection

7.7. Recovery from Recovery from DeadlockDeadlock

8.8. SummarySummary

9.9. ExercisesExercises

Page 24: Operating System Concepts

2424Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.5 Deadlock Avoidance8.5 Deadlock Avoidance

Possible side effects of preventing deadlocksPossible side effects of preventing deadlocks Low device utilizationLow device utilization Reduced system throughputReduced system throughput

Avoid deadlockAvoid deadlock Require additional information about how resources Require additional information about how resources

are to be requestedare to be requested Simplest and most useful modelSimplest and most useful model

Each process declare the Each process declare the maximum numbermaximum number of resources of of resources of each type that it may needeach type that it may need

Possible to ensure that the system will never enter a Possible to ensure that the system will never enter a deadlock statedeadlock state

Page 25: Operating System Concepts

2525Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.5.1 Safe State8.5.1 Safe State

If the system can allocate resources to each process in If the system can allocate resources to each process in some order and still avoid a deadlocksome order and still avoid a deadlock

A A safesafe sequence < sequence <PP11, , PP22, …, , …, PPnn> > for each for each PPii , the resources that , the resources that PPii can still request can be can still request can be

satisfied by currently available resources + resources held by all satisfied by currently available resources + resources held by all the the PPjj , with , with j j < < ii..

If If PPii resource needs are not immediately available, then resource needs are not immediately available, then PPii can can wait until all wait until all PPjj have finished. have finished.

When When PPjj is finished, is finished, PPii can obtain needed resources, execute, can obtain needed resources, execute, return allocated resources, and terminate. return allocated resources, and terminate.

When When PPii terminates, terminates, PPi+1i+1 can obtain its needed resources, and so can obtain its needed resources, and so on. on.

UnsafeUnsafe : no such sequence exists : no such sequence exists

Page 26: Operating System Concepts

2626Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Basic FactsBasic Facts

If a system is in safe stateIf a system is in safe state no deadlocksno deadlocks

If a system is in unsafe stateIf a system is in unsafe state possibility of deadlock.possibility of deadlock.

AvoidanceAvoidance ensure that a system will never ensure that a system will never

enter an unsafe state. enter an unsafe state.

Page 27: Operating System Concepts

2727Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

An ExampleAn Example

A system with 12 magnetic tape drives and 3 processes: A system with 12 magnetic tape drives and 3 processes: PP00, , PP11, and , and PP22

The sequence <The sequence <PP11, , PP00, , PP22> satisfies the safety condition.> satisfies the safety condition.

Maximum NeedsMaximum Needs Current NeedsCurrent Needs

PP00 1010 55

PP11 44 22

PP22 99 22

Page 28: Operating System Concepts

2828Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

An ExampleAn Example

Process Process PP2 2 requests and is allocated 1 more tape driverequests and is allocated 1 more tape drive The system is no longer in a safe state.The system is no longer in a safe state.

If a process requests a resource that is currently If a process requests a resource that is currently available, it may still have to wait.available, it may still have to wait.

Maximum NeedsMaximum Needs Current NeedsCurrent Needs

PP00 1010 55

PP11 44 22

PP22 99 33

Page 29: Operating System Concepts

2929Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.5.2 Resource-Allocation Graph 8.5.2 Resource-Allocation Graph AlgorithmAlgorithm

Resource-allocation graph with only one Resource-allocation graph with only one instance of each resource typeinstance of each resource type Used for deadlock avoidanceUsed for deadlock avoidance

Claim edgeClaim edge PPii -> -> RRjj (represented by a dashed line)(represented by a dashed line) Process Process PPjj may request resource may request resource RRjj

Converts to request edge when a process requests a Converts to request edge when a process requests a resource.resource.

When a resource is released by a process, When a resource is released by a process, assignment edge reconverts to a claim edge.assignment edge reconverts to a claim edge.

Resources must be claimed a priori in the system.Resources must be claimed a priori in the system.

Page 30: Operating System Concepts

3030Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Resource-Allocation GraphResource-Allocation GraphFor Deadlock AvoidanceFor Deadlock Avoidance

Page 31: Operating System Concepts

3131Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Unsafe State InUnsafe State InResource-Allocation GraphResource-Allocation Graph

Page 32: Operating System Concepts

3232Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.5.3 Banker’s Algorithm8.5.3 Banker’s Algorithm

Multiple instancesMultiple instances resource-allocation graph allocation is not applicableresource-allocation graph allocation is not applicable

A new process must declare the maximum number of A new process must declare the maximum number of instances of each resource type that it may need.instances of each resource type that it may need.

Cannot exceed the total number of resources in the systemCannot exceed the total number of resources in the system

Determine whether the allocation of these resources will Determine whether the allocation of these resources will leave the system in a safe stateleave the system in a safe state

If yes, the resources are allocatedIf yes, the resources are allocated If not, the process must wait until some other process releases If not, the process must wait until some other process releases

enough resourcesenough resources

Page 33: Operating System Concepts

3333Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Data StructuresData Structuresfor the Banker’s Algorithmfor the Banker’s Algorithm

Let Let nn = number of processes, and = number of processes, andmm = number of resources types. = number of resources types.

AvailableAvailable:: Vector of length Vector of length mm. If Available[ . If Available[ j j ] = ] = kk, there , there areare k k instances of resource type instances of resource type RRjj available.available.

MaxMax: n x m: n x m matrix. If matrix. If Max Max [ [ i, j i, j ] = ] = kk, then process , then process PPii may may request at mostrequest at most k k instances of resource type instances of resource type RRjj..

AllocationAllocation: n : n xx m m matrix. If Allocation[ matrix. If Allocation[ i, j i, j ] = ] = kk then then P Pii is is currently allocated currently allocated kk instances of instances of RRj.j.

NeedNeed: n : n xx m m matrix. If matrix. If NeedNeed[ [ i, j i, j ] =] = k k, then, then P Pii may need may need kk more instances of more instances of RRjj to complete its task.to complete its task.

NeedNeed [ [ i, j i, j ] = ] = MaxMax[ [ i, j i, j ] – ] – AllocationAllocation [ [ i, j i, j ].].

Page 34: Operating System Concepts

3434Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

NotationNotationfor the Banker’s Algorithmfor the Banker’s Algorithm

Let X and Y be vectors of length Let X and Y be vectors of length nn. . X X ≤≤ Y if and only if X[ Y if and only if X[ i i ] ] ≤ ≤ Y[ Y[ i i ]]

for all for all i i =1,2, …, =1,2, …, nn

For exampleFor example if X = (1, 7, 3, 2) and Y = (0, 3, 2, 1),if X = (1, 7, 3, 2) and Y = (0, 3, 2, 1),

then Y then Y ≤≤ X X

Page 35: Operating System Concepts

3535Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.5.3.1 Safety Algorithm8.5.3.1 Safety Algorithm

Find out whether or not the system is in a safe stateFind out whether or not the system is in a safe state1.1. Let Let Work Work and and FinishFinish be vectors of length be vectors of length m m and and n n, ,

respectively. Initialize:respectively. Initialize:Work :Work := = AvailableAvailable

Finish Finish [ [ i i ] :=] := false false forfor i i = 1, 2, 3, …, = 1, 2, 3, …, n.n.

2.2. Find an Find an i i such that both: such that both: a)a) FinishFinish [ [ i i ] = ] = falsefalse

b)b) NeedNeedii Work.Work.

If no such If no such i i exists, go to step 4.exists, go to step 4.

3.3. WorkWork = = Work Work + + AllocationAllocationii

FinishFinish[ [ i i ] :=] := true truego to step 2.go to step 2.

4.4. If If FinishFinish [ [ i i ] = true for all ] = true for all ii, then the system is in a safe state., then the system is in a safe state.

Page 36: Operating System Concepts

3636Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.5.3.2 Resource-Request 8.5.3.2 Resource-Request AlgorithmAlgorithm

RequestRequesti i [ [ jj ] = k ] = k Process Process PPii wants wants kk instances of resource type instances of resource type RRjj..

1.1. If If RequestRequestii ≤ ≤ NeedNeedii, go to step 2. Otherwise, raise an error condition, , go to step 2. Otherwise, raise an error condition, since the process has exceeded its maximum claim.since the process has exceeded its maximum claim.

2.2. If If RequestRequestii ≤≤ AvailableAvailable, go to step 3. Otherwise , go to step 3. Otherwise PPii must wait, since must wait, since the resources are not available.the resources are not available.

3.3. Pretend to allocate requested resources to Pretend to allocate requested resources to PPii by modifying the state by modifying the state as follows:as follows:

AvailableAvailable := := AvailableAvailable – – RequestRequesti i ;;

AllocationAllocationii := := AllocationAllocationii + + RequestRequestii ; ;

NeedNeedii := := NeedNeedii – – RequestRequestii ; ; If safe -> the resources are allocated to If safe -> the resources are allocated to PPii . . If unsafe -> If unsafe -> PPii must wait, and the old resource-allocation state is must wait, and the old resource-allocation state is

restored.restored.

Page 37: Operating System Concepts

3737Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.5.3.3 An Illustrative Example8.5.3.3 An Illustrative Example

Five processesFive processes PP0 0 through through PP44

Snapshot at time Snapshot at time TT00::AllocationAllocation M a x M a x Available Available NeedNeedA B CA B C A B C A B C A B C A B C A B CA B C

PP00 0 1 00 1 0 7 5 3 7 5 3 3 3 2 3 3 2 7 4 37 4 3PP11 2 0 0 2 0 0 3 2 2 3 2 2 1 2 21 2 2PP22 3 0 2 3 0 2 9 0 29 0 2 6 0 0 6 0 0 PP33 2 1 1 2 1 1 2 2 2 2 2 2 0 1 10 1 1PP44 0 0 20 0 2 4 3 3 4 3 3 4 3 14 3 1

<<PP11, , PP33, , PP44, , PP22, , PP00> satisfies the safety criteria.> satisfies the safety criteria.

Three resource typesThree resource types A A : 10 instances: 10 instances BB : 5 instances : 5 instances CC : 7 instances : 7 instances

Page 38: Operating System Concepts

3838Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.5.3.3 An Illustrative Example8.5.3.3 An Illustrative Example

PP1 1 requestsrequests One instance of resource type AOne instance of resource type A Two instances of resource type CTwo instances of resource type C RequestRequest1 1 = (1, 0, 2) = (1, 0, 2) ≤≤ Available Available (3, 3, 2) (3, 3, 2)

Snapshot at time Snapshot at time TT00::AllocationAllocation Need Need AvailableAvailableA B CA B C A B C A B C A B C A B C

PP00 0 1 00 1 0 7 4 3 7 4 3 2 3 02 3 0 PP11 3 0 23 0 2 0 2 00 2 0 PP22 3 0 2 3 0 2 6 0 06 0 0PP33 2 1 1 2 1 1 0 1 1 0 1 1 PP44 0 0 20 0 2 4 3 1 4 3 1

<<PP11, , PP33, , PP44, , PP00, , PP22> satisfies the safety criteria.> satisfies the safety criteria. Grant the request of processGrant the request of process P P11..

Page 39: Operating System Concepts

3939Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Chapter 8 DeadlocksChapter 8 Deadlocks

1.1. System ModelSystem Model

2.2. Deadlock Deadlock CharacterizationCharacterization

3.3. Methods for Methods for Handling DeadlocksHandling Deadlocks

4.4. Deadlock PreventionDeadlock Prevention

5.5. Deadlock Avoidance Deadlock Avoidance

6.6. Deadlock DetectionDeadlock Detection

7.7. Recovery from Recovery from DeadlockDeadlock

8.8. SummarySummary

9.9. ExercisesExercises

Page 40: Operating System Concepts

4040Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.6 Deadlock Detection8.6 Deadlock Detection

Allow the system to enter deadlock stateAllow the system to enter deadlock state An algorithm that An algorithm that examinesexamines the state of the system to determine the state of the system to determine

whether a deadlock has occurredwhether a deadlock has occurred An algorithm to An algorithm to recoverrecover from the deadlock from the deadlock

A detection-and-recovery scheme requires overheadA detection-and-recovery scheme requires overhead Run-time costsRun-time costs Potential lossesPotential losses

Page 41: Operating System Concepts

4141Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.6.1 Single Instance of8.6.1 Single Instance ofEach Resource TypeEach Resource Type

A A wait-forwait-for graph : obtained from resource-allocation graph graph : obtained from resource-allocation graph Remove the nodes of type resourceRemove the nodes of type resource Collapse the appropriate edgesCollapse the appropriate edges

Page 42: Operating System Concepts

4242Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.6.1 Single Instance of8.6.1 Single Instance ofEach Resource TypeEach Resource Type

A deadlock exists in the system if and only if A deadlock exists in the system if and only if the wait-for graph contains a cycle.the wait-for graph contains a cycle.

To detect deadlocksTo detect deadlocks Maintain the wait-for graphMaintain the wait-for graph Periodically invoke an algorithm that searches for a Periodically invoke an algorithm that searches for a

cycle in the graphcycle in the graph

Page 43: Operating System Concepts

4343Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.6.2 Several Instances of8.6.2 Several Instances ofa Resource Typea Resource Type

The algorithm employs several time-varying The algorithm employs several time-varying data structuresdata structures AvailableAvailable

A vector of length A vector of length mm indicates the number of available indicates the number of available resources of each type.resources of each type.

AllocationAllocationAn An nn x x mm matrix defines the number of resources of each matrix defines the number of resources of each type currently allocated to each process.type currently allocated to each process.

RequestRequestAn An nn x x mm matrix indicates the current request of each matrix indicates the current request of each process. If process. If RequestRequest [ [ii, , jj] = ] = kk, then process , then process PPii is requesting is requesting kk more instances of resource type more instances of resource type RRjj..

Page 44: Operating System Concepts

4444Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Detection AlgorithmDetection Algorithm

1.1. Let Let WorkWork and and FinishFinish be vectors of length be vectors of length mm and and nn, respectively. Initialize:, respectively. Initialize:(a) (a) WorkWork = = AvailableAvailable

(b) For (b) For ii = 1,2, …, = 1,2, …, n n, if , if AllocationAllocationii 0, then 0, then

FinishFinish[i] = false;otherwise, [i] = false;otherwise, FinishFinish[i] = [i] = truetrue..

2.2. Find an index Find an index i i such that both:such that both:(a)(a)FinishFinish[[ii] == ] == falsefalse

(b)(b)RequestRequestii WorkWork

If no such If no such ii exists, go to step 4. exists, go to step 4.

Page 45: Operating System Concepts

4545Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Detection Algorithm (Cont.)Detection Algorithm (Cont.)

3.3. WorkWork = = WorkWork + + AllocationAllocationii

FinishFinish[[ii] = ] = truetruego to step 2.go to step 2.

4.4. If If FinishFinish[[ii] == false, for some ] == false, for some ii, 1 , 1 ii nn, then the system is in , then the system is in deadlock state. Moreover, if deadlock state. Moreover, if FinishFinish[[ii] == ] == falsefalse, then , then PPii is deadlocked. is deadlocked.

Algorithm requires an order of O(m x n2) operations to detect whether the system is in deadlocked state.

Page 46: Operating System Concepts

4646Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Example of Detection AlgorithmExample of Detection Algorithm

Five processes Five processes PP00 through through PP44;; three resource types three resource types

A (7 instances), A (7 instances), B B (2 instances), and (2 instances), and CC (6 instances). (6 instances).

Snapshot at time Snapshot at time TT00::

AllocationAllocation RequestRequest AvailableAvailable

A B C A B C A B C A B C A B CA B C

PP00 0 1 0 0 1 0 0 0 0 0 0 0 0 0 00 0 0

PP11 2 0 0 2 0 0 2 0 22 0 2

PP22 3 0 33 0 3 0 0 0 0 0 0

PP33 2 1 1 2 1 1 1 0 0 1 0 0

PP44 0 0 2 0 0 2 0 0 20 0 2

Sequence <Sequence <PP00, , PP22, , PP33, , PP11, , PP44> will result in > will result in FinishFinish[[ii] = true for all ] = true for all ii. .

Page 47: Operating System Concepts

4747Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Example (Cont.)Example (Cont.)

PP22 requests an additional instance of type requests an additional instance of type C C..

RequestRequest

A B CA B C

PP00 0 0 00 0 0

PP11 2 0 12 0 1

PP22 0 0 10 0 1

PP33 1 0 0 1 0 0

PP44 0 0 20 0 2

State of system?State of system? Can reclaim resources held by process Can reclaim resources held by process PP00, but insufficient resources to , but insufficient resources to

fulfill other processes; requests.fulfill other processes; requests. Deadlock exists, consisting of processes Deadlock exists, consisting of processes PP11, , PP22, , PP33, and , and PP44..

Page 48: Operating System Concepts

4848Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.6.3 Detection-Algorithm Usage8.6.3 Detection-Algorithm Usage

When, and how often, to invoke depends on:When, and how often, to invoke depends on: How How oftenoften a deadlock is likely to occur? a deadlock is likely to occur? How How manymany processes will need to be rolled back? processes will need to be rolled back?

one for each disjoint cycleone for each disjoint cycle

The The detection algorithm can be invokeddetection algorithm can be invoked When a request canWhen a request cannot be granted immediatelynot be granted immediately

Identify Identify the specific process that caused the deadlockthe specific process that caused the deadlock At arbitrary points in timeAt arbitrary points in time

Not be able to tell which of the many deadlocked processes Not be able to tell which of the many deadlocked processes “caused” the deadlock“caused” the deadlock

Page 49: Operating System Concepts

4949Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Chapter 8 DeadlocksChapter 8 Deadlocks

1.1. System ModelSystem Model

2.2. Deadlock Deadlock CharacterizationCharacterization

3.3. Methods for Methods for Handling DeadlocksHandling Deadlocks

4.4. Deadlock PreventionDeadlock Prevention

5.5. Deadlock Avoidance Deadlock Avoidance

6.6. Deadlock DetectionDeadlock Detection

7.7. Recovery from Recovery from DeadlockDeadlock

8.8. SummarySummary

9.9. ExercisesExercises

Page 50: Operating System Concepts

5050Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.7.1 Process Termination8.7.1 Process Termination

Abort all deadlocked processes.Abort all deadlocked processes.Abort one process at a time until the deadlock cycle is Abort one process at a time until the deadlock cycle is eliminated.eliminated.

In which order should we choose to abort?In which order should we choose to abort? Priority of the process.Priority of the process. How long process has computed, and how much longer to How long process has computed, and how much longer to

completion.completion. Resources the process has used.Resources the process has used. Resources process needs to complete.Resources process needs to complete. How many processes will need to be terminated. How many processes will need to be terminated. Is process interactive or batch?Is process interactive or batch?

Page 51: Operating System Concepts

5151Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

8.7.2 Resource Preemption8.7.2 Resource Preemption

Three issuesThree issues Selecting a victimSelecting a victim

To minimize costTo minimize cost Number of resourcesNumber of resources Amount of timeAmount of time

RollbackRollbackReturn to some safe state, restart process for that stateReturn to some safe state, restart process for that stateThe simplest solution is a total rollbackThe simplest solution is a total rollback

StarvationStarvationSame process may always be picked as victim, include Same process may always be picked as victim, include number of rollback in cost factornumber of rollback in cost factor

Include the number of rollbacks in the cost factorInclude the number of rollbacks in the cost factor

Page 52: Operating System Concepts

5252Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Chapter 8 DeadlocksChapter 8 Deadlocks

1.1. System ModelSystem Model

2.2. Deadlock Deadlock CharacterizationCharacterization

3.3. Methods for Methods for Handling DeadlocksHandling Deadlocks

4.4. Deadlock PreventionDeadlock Prevention

5.5. Deadlock Avoidance Deadlock Avoidance

6.6. Deadlock DetectionDeadlock Detection

7.7. Recovery from Recovery from DeadlockDeadlock

8.8. SummarySummary

9.9. ExercisesExercises

Page 53: Operating System Concepts

5353Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

SummarySummary

P.266P.266

Page 54: Operating System Concepts

5454Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

Chapter 8 DeadlocksChapter 8 Deadlocks

1.1. System ModelSystem Model

2.2. Deadlock Deadlock CharacterizationCharacterization

3.3. Methods for Methods for Handling DeadlocksHandling Deadlocks

4.4. Deadlock PreventionDeadlock Prevention

5.5. Deadlock Avoidance Deadlock Avoidance

6.6. Deadlock DetectionDeadlock Detection

7.7. Recovery from Recovery from DeadlockDeadlock

8.8. SummarySummary

9.9. ExercisesExercises

Page 55: Operating System Concepts

5555Ku-Yaw ChangKu-Yaw Chang Chapter 8 DeadlocksChapter 8 Deadlocks

ExercisesExercises

8.28.2

8.48.4

8.58.5

8.128.12

8.138.13

Page 56: Operating System Concepts

The EndThe End