34
1 Deadlocks Deadlocks 3.1. Resource 3.2. Introduction to deadlocks 3.3. The ostrich algorithm 3.4. Deadlock detection and recovery 3.5. Deadlock avoidance 3.6. Deadlock prevention 3.7. Other issues

Deadlocks

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Deadlocks

1

DeadlocksDeadlocks

3.1. Resource 3.2. Introduction to deadlocks 3.3. The ostrich algorithm 3.4. Deadlock detection and recovery 3.5. Deadlock avoidance 3.6. Deadlock prevention 3.7. Other issues

Page 2: Deadlocks

2

ResourcesResources

• Examples of computer resourcesExamples of computer resources– printersprinters– tape drivestape drives– tablestables

• Processes need access to resources in Processes need access to resources in reasonable orderreasonable order

• Suppose a process holds resource A and Suppose a process holds resource A and requests resource Brequests resource B– at same time another process holds B and at same time another process holds B and

requests Arequests A– both are blocked and remain soboth are blocked and remain so

Page 3: Deadlocks

3

Resources (1)Resources (1)• Deadlocks occur when …Deadlocks occur when …

– processes are granted exclusive processes are granted exclusive access to devicesaccess to devices

– we refer to these devices generally we refer to these devices generally as as resourcesresources

• Preemptable resourcesPreemptable resources– can be taken away from a process can be taken away from a process

with no ill effectswith no ill effects• Nonpreemptable resourcesNonpreemptable resources

– will cause the process to fail if will cause the process to fail if taken awaytaken away

Page 4: Deadlocks

4

Resources (2)Resources (2)• Sequence of events required to Sequence of events required to

use a resourceuse a resource

(example: using of Semaphore)(example: using of Semaphore)1.1. request the resourcerequest the resource

2.2. use the resourceuse the resource

3.3. release the resourcerelease the resource

• Must wait if request is deniedMust wait if request is denied– requesting process may be requesting process may be

blockedblocked– may fail with error codemay fail with error code

Page 5: Deadlocks

5

Introduction to Introduction to DeadlocksDeadlocks

• Formal definition :Formal definition :A set of processes is deadlocked if A set of processes is deadlocked if each process in the set is waiting for each process in the set is waiting for an event that only another process in an event that only another process in the set can causethe set can cause

• Usually the event is release of a currently Usually the event is release of a currently held resourceheld resource

• None of the processes can …None of the processes can …– runrun– release resourcesrelease resources– be awakenedbe awakened

Page 6: Deadlocks

6

Four Coffman Conditions for Four Coffman Conditions for DeadlockDeadlock

(Without one of them no deadlock (Without one of them no deadlock is possible) is possible) 1.1. Mutual exclusion conditionMutual exclusion condition

• each resource assigned to 1 process or is each resource assigned to 1 process or is availableavailable

2.2. Hold and wait conditionHold and wait condition• process holding resources can request additionalprocess holding resources can request additional

3.3. No preemption conditionNo preemption condition• previously granted resources cannot forcibly previously granted resources cannot forcibly

taken awaytaken away4.4. Circular wait conditionCircular wait condition• must be a circular chain of 2 or more processesmust be a circular chain of 2 or more processes• each is waiting for resource held by next member each is waiting for resource held by next member

of the chainof the chain

Page 7: Deadlocks

7

Deadlock Modeling (2)Deadlock Modeling (2)

• Modeled with directed graphsModeled with directed graphs

– resource R assigned to process Aresource R assigned to process A– process B is requesting/waiting for resource Sprocess B is requesting/waiting for resource S– process C and D are in deadlock over resources T process C and D are in deadlock over resources T

and Uand U

Page 8: Deadlocks

8

Deadlock Modeling (3)Deadlock Modeling (3)

Strategies for dealing with Strategies for dealing with DeadlocksDeadlocks

1.1. just ignore the problem altogetherjust ignore the problem altogether

2.2. detection and recoverydetection and recovery

3.3. dynamic avoidance dynamic avoidance • careful resource allocationcareful resource allocation

4.4. prevention prevention • negating one of the four necessary negating one of the four necessary

conditionsconditions

Page 9: Deadlocks

9How deadlock occursHow deadlock occurs

A B CDeadlock Modeling (4)Deadlock Modeling (4)

Page 10: Deadlocks

10

Deadlock Modeling (5)Deadlock Modeling (5)

How deadlock can be avoidedHow deadlock can be avoided

(o) (p) (q)

Page 11: Deadlocks

11

The Ostrich AlgorithmThe Ostrich Algorithm• Pretend there is no problemPretend there is no problem• Reasonable if Reasonable if

– deadlocks occur very rarely deadlocks occur very rarely – cost of prevention is highcost of prevention is high

• UNIX and Windows takes this UNIX and Windows takes this approachapproach

• It is a trade off between It is a trade off between – convenienceconvenience– correctnesscorrectness

Page 12: Deadlocks

12

Detection with One Resource Detection with One Resource of Each Type (1)of Each Type (1)

Process A holds R and wants S. Process B holds nothing but wants T. Process C holds nothing but wants S. Process D holds U and wants S and T. Process E holds T and wants V. Process F holds W and wants S. Process G holds V and wants U. The question is: “Is this system deadlocked,

and if so, which processes are involved?”

Page 13: Deadlocks

13

Detection with One Resource of Detection with One Resource of Each Type (2)Each Type (2)

• Note the resource ownership and requestsNote the resource ownership and requests• A cycle can be found within the graph, A cycle can be found within the graph,

denoting deadlockdenoting deadlock

Page 14: Deadlocks

14

The AlgorithmThe AlgorithmFor each node perform the following 5

steps:1. Initialize L and designate all the arcs; 2. Add the current node to the L and

check if the node appears in two times. If so, the graph contains a cycle (listed in L). Stop.

3. From the given node, see if there any unmarked outgoing arcs. If so, go to 4; if not, go to 5.

4. Mark an unmarked outgoing arc at random. Then follow it to the new node and go to 2.

5. It’s a dead end. Remove it and go back to the previous node go to step 2. If this node is the initial one, the graph does not contain any cycles. Stop.

Page 15: Deadlocks

15

Detection with Multiple Resources Detection with Multiple Resources of Each Type (1)of Each Type (1)

Data structuresData structures needed by deadlock detection algorithm needed by deadlock detection algorithm

Page 16: Deadlocks

16

Deadlock detection Deadlock detection algorithmalgorithm

The deadlock detection algorithm can now be The deadlock detection algorithm can now be given, as follows:given, as follows:

1.1. Look for an unmarked process, Look for an unmarked process, PPi i ,, for for which the iwhich the ithth row of row of R R is less than or equal is less than or equal to to AA. .

2.2. If such a process is found, add the iIf such a process is found, add the ithth row of row of CC to to AA, mark the process, and go back to , mark the process, and go back to step 1. step 1.

3.3. If no such process exists, the algorithm If no such process exists, the algorithm terminates. terminates.

When the algorithm finishes, all the unmarked When the algorithm finishes, all the unmarked processes, if any, are deadlocked.processes, if any, are deadlocked.

Page 17: Deadlocks

17

Detection with Multiple Resources Detection with Multiple Resources of Each Type (2)of Each Type (2)

An example for the deadlock detection algorithmAn example for the deadlock detection algorithm

Page 18: Deadlocks

18

Recovery from Deadlock (1)Recovery from Deadlock (1)(recovery after detecting)(recovery after detecting)

• Recovery through preemptionRecovery through preemption– take a resource from some other take a resource from some other

processprocess(Laser printer can be taken if (Laser printer can be taken if operator collects all printed papers)operator collects all printed papers)

– depends on nature of the resourcedepends on nature of the resource• Recovery through rollbackRecovery through rollback

– checkpointcheckpoint a process periodically a process periodically– use this saved state use this saved state – restart the process if it is found restart the process if it is found

deadlockeddeadlocked

Page 19: Deadlocks

19

Recovery from Deadlock Recovery from Deadlock (2)(2)

• Recovery through killing processesRecovery through killing processes– crudest but simplest way to break a crudest but simplest way to break a

deadlockdeadlock– kill one of the processes in the kill one of the processes in the

deadlock cycledeadlock cycle– the other processes get its resources the other processes get its resources – choose process that can be rerun from choose process that can be rerun from

the beginningthe beginning

Page 20: Deadlocks

20

Deadlock Deadlock AvoidanceAvoidanceResource TrajectoriesResource Trajectories

Two process resource trajectoriesTwo process resource trajectories

Page 21: Deadlocks

21

Safe and Unsafe States Safe and Unsafe States (1)(1)

Demonstration that the state in (a) is safeDemonstration that the state in (a) is safe

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

Page 22: Deadlocks

22

Safe and Unsafe States Safe and Unsafe States (2)(2)

Demonstration that the state in (b) is not safe (this Demonstration that the state in (b) is not safe (this situation is a result of giving one resource to A) situation is a result of giving one resource to A)

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

Note: Note: The difference between a safe state and The difference between a safe state and an unsafe state is that from a safe state the an unsafe state is that from a safe state the system can system can guaranteeguarantee that all processes will that all processes will finish. finish.

Page 23: Deadlocks

23

The Banker's Algorithm for a The Banker's Algorithm for a Single ResourceSingle Resource

• Three resource allocation statesThree resource allocation states– safesafe– safesafe– unsafeunsafe

(a) (b) (c)

Page 24: Deadlocks

24

Banker's Algorithm for Multiple Banker's Algorithm for Multiple ResourcesResources

Example of banker's algorithm with multiple Example of banker's algorithm with multiple resources resources

(E – existed; P – possessed; A – available.)(E – existed; P – possessed; A – available.)In practice processes rarely know in advance what In practice processes rarely know in advance what

their maximum resource needs will be.their maximum resource needs will be.

Page 25: Deadlocks

25

The Banker’s Algorithm for The Banker’s Algorithm for Multiple Resources Multiple Resources

The algorithm for checking to see if a state The algorithm for checking to see if a state is safe can now be stated:is safe can now be stated:

1.1. Look for a row, Look for a row, RR, whose unmet resource , whose unmet resource needs are all smaller than or equal to needs are all smaller than or equal to AA. . If no such row exists, the system will If no such row exists, the system will eventually deadlock since no process can eventually deadlock since no process can run to completion. run to completion.

2.2. Assume the process of the row chosen Assume the process of the row chosen requests all the resources it needs (which requests all the resources it needs (which is guaranteed to be possible) and finishes. is guaranteed to be possible) and finishes. Mark that process as terminated and add Mark that process as terminated and add all its resources to the all its resources to the A A vector. vector.

3.3. Repeat steps 1 and 2 until either all Repeat steps 1 and 2 until either all processes are marked terminated, in processes are marked terminated, in which case the initial state was safe, or which case the initial state was safe, or until a deadlock occurs, in which case it until a deadlock occurs, in which case it was not. was not.

Page 26: Deadlocks

26

Banker's Algorithm for Multiple Banker's Algorithm for Multiple ResourcesResources(example)(example)

Example of banker's algorithm with multiple Example of banker's algorithm with multiple resources resources

(E – existed; P – possessed; A – available.)(E – existed; P – possessed; A – available.)In practice processes rarely know in advance what In practice processes rarely know in advance what

their maximum resource needs will be.their maximum resource needs will be.

Page 27: Deadlocks

27

Deadlock PreventionDeadlock PreventionAttacking the Mutual Exclusion Attacking the Mutual Exclusion

ConditionCondition• Some devices (such as printer) can be Some devices (such as printer) can be

spooledspooled– only the printer daemon uses printer only the printer daemon uses printer

resourceresource– thus deadlock for printer eliminatedthus deadlock for printer eliminated

• Not all devices can be spooledNot all devices can be spooled• Principle:Principle:

– avoid assigning resource when not avoid assigning resource when not absolutely necessaryabsolutely necessary

– as few processes as possible actually as few processes as possible actually claim the resourceclaim the resource

Page 28: Deadlocks

28

Attacking the Hold and Wait Attacking the Hold and Wait ConditionCondition

• Require processes to request resources Require processes to request resources before startingbefore starting– a process never has to wait for what it needsa process never has to wait for what it needs

• ProblemsProblems– may not know required resources at start of runmay not know required resources at start of run– also ties up resources other processes could be also ties up resources other processes could be

usingusing

• Variation: Variation: – process must give up all resourcesprocess must give up all resources– then request all immediately neededthen request all immediately needed

Page 29: Deadlocks

29

Attacking the No Preemption Attacking the No Preemption ConditionCondition

• This is not a viable option (This is not a viable option (keçilməz)keçilməz)• Consider a process given the printerConsider a process given the printer

– halfway through its jobhalfway through its job– now forcibly take away printernow forcibly take away printer– !!??!!??

Page 30: Deadlocks

30

Attacking the Circular Wait Attacking the Circular Wait Condition (1)Condition (1)

• Normally ordered resourcesNormally ordered resources

((If If ii <  < jj, then , then B B is not allowed to is not allowed to request request i i ))

• Use aUse a resource graph resource graph

(a) (b)

Page 31: Deadlocks

31

SummarySummary

Summary of approaches to deadlock preventionSummary of approaches to deadlock prevention

Page 32: Deadlocks

32

Other IssuesOther IssuesTwo-Phase Locking (For DB Two-Phase Locking (For DB

systems)systems)• Phase OnePhase One

– process tries to lock all records it needs, one process tries to lock all records it needs, one at a timeat a time

– if needed record found locked, start overif needed record found locked, start over– (no real work done in phase one)(no real work done in phase one)

• If phase one succeeds, it starts second phase, If phase one succeeds, it starts second phase, – performing updatesperforming updates– releasing locks releasing locks

• Note similarity to requesting all resources at Note similarity to requesting all resources at onceonce

• Algorithm works where programmer can arrangeAlgorithm works where programmer can arrange– program can be stopped, restartedprogram can be stopped, restarted

Page 33: Deadlocks

33

Nonresource DeadlocksNonresource Deadlocks

• Possible for two processes to Possible for two processes to deadlockdeadlock– each is waiting for the other to do some each is waiting for the other to do some

tasktask

• Can happen with semaphoresCan happen with semaphores– each process required to do a each process required to do a down()down() on on

two semaphores (two semaphores (mutexmutex and another) and another)– if done in wrong order, deadlock resultsif done in wrong order, deadlock results

Page 34: Deadlocks

34

StarvationStarvation• Algorithm to allocate a resource Algorithm to allocate a resource

– may be to give to shortest job firstmay be to give to shortest job first

• Works great for multiple short jobs in a systemWorks great for multiple short jobs in a system

• May cause long job to be postponed May cause long job to be postponed indefinitelyindefinitely– even though not blockedeven though not blocked

• Solution:Solution:– First-come, first-serve policyFirst-come, first-serve policy