Вы находитесь на странице: 1из 11

Chapter 6

Deadlocks
1. OVERVIEW A set of blocked processes each holding a
resource and waiting to acquire a resource
1.1. Objective
held by another process in the set.
After reading this chapter, you should
understand: A process requests resources; if the resources
are not available at that time, the process
 the problem of deadlock.
enters a wait state. It may happen that
 the four necessary conditions for deadlock
waiting processes will never again change
to exist.
state, because the resources they have
 the problem of indefinite postponement.
requested are held by other waiting
 the notions of deadlock prevention,
processes. This situation is called a deadlock.
avoidance, detection and recovery.
 algorithms for deadlock avoidance and
detection.
 how systems can recover from deadlocks

1.2. Definitions

A process or thread is in a state of deadlock


(or is deadlocked) if it is waiting for a
particular event that will not occur.
A set of processes have a deadlock if each
process is waiting for an event that only
another process in the set can cause.

Deadlock is a situation wherein each of a


collection of processes is waiting for some
event to occur from other processes in the
collection. Since all are waiting, none can
provide any of the things being waited for. Resources

To generalize our discussion we would take A resource can be a Computer hardware


events as computer resources, since most that includes the CPU, RAM, ROM, memory
deadlocks in operating systems develop disks, disk drives, peripheral devices like
because of the normal contention for printers, scanners; or data and information
dedicated resources, i.e., resources that such as files, softwares (system or
may be used over by many processes but by application), a database, a record within a
only one process at a time, sometimes called database or file, a shared variable, a critical
serially reusable resources. For example, a section etc, that are used by processes as and
printer can print jobs for only one process at a when required depending upon the task they
time (otherwise pieces of many print jobs intend to perform.
would be interwoven). Resources come are of two types preemptable
and nonpreemptable.
A preemptable resource is one which can
be allocated to a given process for a period of
2  Essentials of Operating System

time, then can be taken away and allocated to Request: The process requests the resource.
another process and then be reallocated to If the request cannot be granted immediately
the first process without any ill effects. (for example, if the resource is being used by
Memory, buffers, CPU, array processor etc are another process), then the requesting process
some preemptable resources. must wait until it can acquire the resource.
For example, a system with 32 MB of user Use: The process can operate on the resource
memory, one printer, and two 32-MB (for example, if the resource is a printer, the
processes that each want to print something. process can print on the printer).
Process A request and gets the printer, then
Release: The process releases the resource.
start to compute the values to print. Before it
has finished with the computation, it exceeds
its time quantum and is swapped out.
Process B now runs and tires, unsuccessfully,
to acquire the printer. Potentially, we now
have a deadlock situation, because A has the
printer and B has the memory, and neither
2. CONDITIONS NECESSARY FOR
can proceed without the resource held by the
DEADLOCK
other. Fortunately, it is possible to preempt
(take away) the memory from B by swapping
it out and swapping A in. Now A can run, do  Mutual exclusions
its printing, and then release the printer. No  Hold and wait
deadlock occurs.  No preemption
 Circular wait
A nonpreemptable resource is the one that
cannot be taken away from the current
process and given to another without causing In 1971 Coffman et al. showed that four
side effects or may even fail the computation conditions must hold in order for deadlock to
altogether. Eg. Disks, files, mutex etc. CD occur:
recorders are not preemptable at an arbitrary 1. Mutual exclusions: A resource may be
moment. Service Request Block (SRB) which acquired exclusively by only one process at
represents a request for a system service are a time
often non-preemptable.
2. Hold and wait: Processes that currently
If a process has begun to burn a CD-ROM, hold resources can request and wait for
suddenly taking the CD recorder away from it additional resources which are currently
and giving it to another process will result in a held by other processes.
garbled CD. 3. No preemption: Resources previously
Each process utilizes a resource as follows: granted cannot be taken away from the
processes that hold them; they must be
voluntarily released by the holding process.
That is, Once a process has obtained a
resource, the system cannot remove it
from the process's control until the process
has finished using the resource.
4. Circular wait: Two or more processes are
locked in a "circular chain" in which each
process is waiting for one or more
resources that the next process in the
chain is holding.
Eg. P0 is waiting for a resource held
by P1 who is waiting for a resource held
U by Pj ... who is waiting for a resource held
by P(n-1) which is waiting for a resource held
by Pn which is waiting for a resource held
by P0.
Introduction to Operating System  3

All four of these conditions must hold


simultaneously for deadlock to occur.
Circular wait implies the hold and wait
condition. Therefore, these conditions are
not completely independent.

Starvation is the problem that occurs


when a process is waiting for a resource
that is allocated to other processes,
released, and then allocated again to some
process other than the one that is starving. Fig: Pi requests an instance of Rj
 A directed edge from a dot within a
resource vertex (an instance of the
Resource Allocation Graph Syntax
resource Rj) to a process vertex (Pi)
We can use a directed graph called indicates that the resource has been
a resource-allocation graph to characterize allocated to the process. This is called
a deadlock situation. A resource allocation a assignment edge.
graph contains a set of vertices V and a set of
edges E.
 Vertices represent resources and processes.
P = {P1, P2, ..., Pn} is the set of all processes.
R = {R1, R2, ..., Rm} is the set of all resources.
 A process is represented by a Circular
vertices. Fig: Pi is holding an instance of Rj

Fig: Process
 A rectangular vertices is used to
represent resource classes, with dots
within the vertex to represent instances of Some Resource Allocation Graphs
the resource.  resource allocation graph without
deadlock:
o P1 wants a resource held by P2
o no process is requesting an
instance of R4

Fig: Resource type with four instances

 A directed edge from a process vertex (Pi)


to a resource vertex (Rj) indicates that the
process has requested an instance of the
resource. This is called a request edge.

(regenerated from [OSC8] Fig. 7.2 on p. 288)


4  Essentials of Operating System

 resource allocation graph with a cycle


and deadlock:

A deadlock. A holds tape and disk, then


requests for a printer, B holds printer, then
(regenerated from [OSC8] Fig. 7.3 on p. 289) requests for tape and disk
 resource allocation graph with a cycle
but no deadlock: Resource Allocation Graph Summary
 If a resource allocation graph does not
contain a cycle, then there is absolutely no
possibility of deadlock
 If a resource allocation graph contains a
cycle, then there is the possibility of
deadlock. Therefore, a cycle means
deadlock is possible, but not
necessarily present.
 If each resource type has exactly one
instance, then a cycle implies that deadlock
has occurred
 If the cycle involves only a set of resource
types, each of which has only a single
instance, then a deadlock has occurred
 If all instances of a resource are allocated
to a process in a cycle, then there is
deadlock
(regenerated from [OSC8] Fig. 7.4 on p.
289) Methods for Handling Deadlock
In general, there are four strategies of dealing
with deadlock problem:
1. The Ostrich Approach

Just ignore the deadlock problem altogether.


Approached used by many operating systems
including UNIX and Windows, and the Java
VM.
2. 2. Deadlock Detection and Recovery
Introduction to Operating System  5

Detect deadlock and, when it occurs, take This approach to the deadlock problem
steps to recover. Allow the system to enter a anticipates deadlock before it actually occurs.
deadlocked state, then deal with and eliminate
This approach employs an algorithm to access
the problem
the possibility that deadlock could occur and
3. 3. Deadlock Avoidance
acting accordingly.
Avoid deadlock by careful resource It differs from deadlock prevention, which
scheduling. Anticipates deadlock before it guarantees that deadlock cannot occur by
actually occurs. denying one of the necessary conditions of
4. 4. Deadlock Prevention deadlock.

Prevent deadlock by resource scheduling so as This requires that the system has some
to negate at least one of the four conditions. information available up front.
Now we consider each strategy in order of  Each process declares in advance, the
decreasing severity. maximum number of resources of each type
that it may need.
Deadlock Prevention  Dynamically examine the resource
By ensuring that at least one of these allocation state to ensure that there can
conditions cannot hold, we can prevent the never be a circular-wait condition.
occurrence of a deadlock  The system's resource-allocation state is
 Mutual Exclusion – Not required for defined by the number of available and
sharable resources; must hold for allocated resources, and the maximum
nonsharable resources. Spooling can possible demands of the processes.
convert serially reusable devices into  When a process requests an available
seemingly shareable virtual devices as in resource, the system must decide if
case of printers, thus denying the mutual immediate allocation leaves the system in
exclusion precondition. a safe state.
 Hold and Wait – must guarantee that
whenever a process requests a resource, it That is,
does not hold any other resources. o Do not start a process it its maximum
o Require process to request and be requirement might lead to deadlock.
allocated all its resources before it begins o Do not grant an incremental resource
execution, or allow process to request request if this allocation might lead to
resources only when the process has deadlock.
none.
o Low resource utilization; starvation Safe State
possible.
 No Preemption – If a process that is  The key to a state being safe is that there is
holding some resources requests another at least one way for all users to finish.
resource that cannot be immediately  The system is in a safe state if there exists
allocated to it, then all resources currently a safe sequence of all processes P1, P2, P3 …
being held are released. Pn, where, for each Pi, the resources which
o Preempted resources are added to the list Pi can still request can be satisfied by
of resources for which the process is o the currently available resources plus
waiting. o the resources held by all of the Pj's,
o Process will be restarted only when it can where j < i.
regain its old resources, as well as the  If Pi resource needs are not immediately
new ones that it is requesting. available, then Pi can wait
 Circular Wait – impose a total ordering of  until all Pj have finished.
all resource types, and require that each
 When Pj is finished, Pi can obtain needed
process requests resources in an increasing
resources, execute,
order of enumeration.
 return allocated resources, and terminate.
 When Pi terminates, Pi+1 can obtain its
Deadlock Avoidance
needed resources, and so on.
6  Essentials of Operating System

Process Maximum Holding Needs


Example: Consider a system with 12 Needs
magnetic tapes and 3 processes (P0, P1, and P0 10 5 5
P2): P1 4 2 2
Currently available/ unused resources/ P2 9 3 6
magnetic tapes = 3
Process Maximum Holding Needs
Needs This is an unsafe system, since only P1 can be
P0 10 5 5 allocated its maximum needs.
P1 4 2 2 Even if, when P1 releases its all the 4
P2 9 2 7 resources after job completion, that will not
suffice the needs of either P0 or P2, resulting in
a deadlock.
The system is currently in a safe state.
And this is how-
Step 1: P1's maximum need is 4, it holds 2  If a system is in safe state, there is no
and needs 2. This need can be fulfilled by the deadlocks.
3 available resources. i.e. P1 will become  If a system is in unsafe state, there is a
Process Maximum Holding Needs possibility of deadlock.
Needs  Avoidance: ensure that a system will never
P1 4 4 0 enter an unsafe state.
Now available is 1
After having completed the job, P1 will release
the 4 resources its holding.
Now available will be 1 + 4 = 5
Step 2: Now P0's maximum need is 10, its
holding 5 and needs 5. This need can be
fulfilled by the 5 available resources i.e. p0
will become
Process Maximum Holding Needs
Needs
P0 10 10 0
Now available is 0
After having completed the job, P0 will release
the 10 resources its holding.
Now available will be 0 + 10 = 10
Step 3: Now P2's maximum need is 9, its
holding 2 and needs 7. This need can be
fulfilled from the 10 available resources.
Thus, there is a way for all processes to finish DEADLOCK AVOIDANCE ALGORITHM
and the safe sequence being
< P1, P0, P2 > Two deadlock avoidance algorithms:
Unsafe State  Resource-allocation graph algorithm
If there is no allocation sequence that allows  Banker's algorithm
the processes to finish executing, then the
system is in an unsafe state. RAGL
All safe states are deadlock free, but not
all unsafe states lead to deadlocks. Resource-allocation graph algorithm
 Only applicable when we only have 1
Example: In the above example suppose P2 instance of each resource type
requests and is allocated 1 more tape drive.  Claim edge (dotted edge), like
Now the situation would be a future request edge. Claim edge Pi Rj
Currently available/unused indicated that process Pj may request
resources/magnetic tapes = 2 resource Rj; represented by a dashed line.
Introduction to Operating System  7

 When a process requests a resource, the


claim edge is converted to a request edge.
 Request edge converted to an assignment
edge when the resource is allocated to the
process.
 When a process releases a resource, the
assignment edge is reconverted to a claim
edge
 Resources must be claimed a priori in the
system.
 Cycle detection: O(n²)

Suppose that process Pi requests a


resource Rj
The request can be granted only if:
converting the request edge to an
assignment edge
does not result in the formation of a cycle in
the resource allocation graph

Banker's Algorithm
Banker’s algorithm is a deadlock avoidance
algorithm. It is named so because this
algorithm is used in banking systems to
determine whether a loan can be granted or
not.
Consider there are n account holders in a
bank and the sum of the money in all of their
accounts is S. Everytime a loan has to be
granted by the bank, it subtracts the loan
amount from the total money the bank has.
Then it checks if that difference is greater
than S. It is done because, only then, the
bank would have enough money even if all the
n account holders draw all their money at
once.
Banker’s algorithm works in a similar way in
computers. Whenever a new process is
Example:
created, it must exactly specify the maximum
instances of each resource type that it needs.
8  Essentials of Operating System

 For both single and multiple instances per 3. Otherwise, pretend to allocate the
resource types requested resources to Pi :
 The resource manager must know in 4. available[j] = available[j] -
advance the maximum needs of all the request[i][j]
processes. 5. allocation[i][j] = allocation[i][j] +
 Processes request 1 resource at a time request[i][j]
 Request granted ONLY if it results in a safe need[i][j] = need[i][j] - request[i][j]
state i.e. the request plus current usage of
the processes is less than the need after Once the resources are allocated, check to see
allocating the request there exists a if the system state is safe. If unsafe, the
sequence in which all processes can run to process must wait and the old resource-
completion even if they demand their full allocated state is restored.
claim. Safety algorithm (to check for a safe
 If request results in an unsafe state, it is state):
denied and user holds resources and waits 1. Let work be an integer array of length m,
until request is eventually satisfied initialized to available.
 Users must guarantee to release resources Let finish be a boolean array of length n,
in finite time initialized to false.
2. Find an i such that both:
 Resource manager guarantees to allocate
resources in finite time Process
o finish[i] == false
o need[i] <= work
If no such i exists, go to step 4
3. work = work + allocation[i];
Let us assume that there are n processes
finish[i] = true;
and m resource types. Some data structures
Go to step 2
are used to implement the banker’s algorithm.
4. If finish[i] == true for all i, then the
They are:
system is in a safe state, otherwise unsafe.
We call Banker's algorithm when a request for
Run-time complexity: O(m × n²).
R is made. Let n be the number of processes
Example: consider a system with 5 processes
in the system, and m be the number of
(P0 ... P4) and 3 resources types (A(10) B(5)
resource types.
C(7))
resource-allocation state at time t0:
Define:
Process Allocation Max Need Available
 available[m]: the number of units of R
currently unallocated (e.g., available[3] = A B C A B C A B C A B C
2) P0 0 1 0 7 5 3 7 4 3 3 3 2
 max[n][m]: describes the maximum P1 2 0 0 3 2 2 1 2 2
demands of each process (e.g., max[3][1]
= 2) P2 3 0 2 9 0 2 6 0 0
 allocation[n][m]: describes the current P3 2 1 1 2 2 2 0 1 1
allocation status ( e.g., allocation[5][1] = P4 0 0 2 4 3 3 4 3 1
3) Is the system in a safe state? If so, which
 need[n][m]: describes sequence satisfies the safety criteria?
the remaining possible need (i.e., need[i][j] < P1, P3, P4, P2, P0 >
= max[i][j] - allocation[i][j]) Now suppose, P1 requests an additional
instance of A and 2 more instances of type C.
Resource-request algorithm: request[1] = (1,0,2)
1. check if request[1] <= need[i] (yes)
Define: 2. check if request[1] <= available[i] (yes)
 request[n][m]: describes the current 3. do pretend updates to the state
outstanding requests of all processes
Process Allocation Max Need Available
(e.g., request[2][1] = 3)
1. If request[i][j] <= need[i][j], to to step 2; A B C A B C A B C A B C
otherwise, raise an error condition. P0 0 1 0 7 5 3 7 4 3 3 3 2
2. If request[i][j] > available[j], then the P1 3 0 2 3 2 2 0 2 0
process must wait.
Introduction to Operating System  9

P2 3 0 2 9 0 2 6 0 0  Successively kill processes until the system


P3 2 1 1 2 2 2 0 1 1 is deadlock free.
P4 0 0 2 4 3 3 4 3 1 These methods are expensive in the sense
Is the system in a safe state? If so, which that each iteration calls the detection
sequence satisfies the safety criteria? algorithm until the system proves to be
<P1, P3, P4, P0, P2> deadlock free. The complexity of algorithm
Hence, we immediately grant the request. is O(N2) where N is the number of proceeds.
Another potential problem is starvation; same
Will a request of (3,3,0) by P4 be granted? process killed repeatedly.

 Advantage: Avoids deadlock and it is less


restrictive than deadlock prevention. Recovery from Deadlock: Process
 Disadvantage: Only works with fixed Termination
number of resources and processes.  Abort all deadlocked processes.
 Guarantees finite time - not reasonable  Abort one process at a time until the
response time deadlock cycle is eliminated.
 Needs advanced knowledge of maximum  In which order should we choose to abort?
needs - Priority of the process.
 Not suitable for multi-access systems - How long process has computed, and
 Unnecessary delays in avoiding unsafe how much longer to completion.
states which may not lead to deadlock - Resources the process has used.
- Resources process needs to complete.
- How many processes will need to be
DEADLOCK DETECTION terminated.
https://www.cs.jhu.edu/~yairamir/cs41 - Is process interactive or batch?
8/os4/sld028.htm
If a system does not employ either a Recovery from Deadlock: Resource
deadlock-prevention or a deadlock avoidance Preemption
algorithm, then a deadlock situation may  Selecting a victim – minimize cost.
occur. In this environment, the system must  Rollback – return to some safe state, restart
provide: process for that state.
 An algorithm that examines the state of  Starvation – same process may always be
the system to determine whether a picked as victim, include number of rollback
deadlock has Occurred. in cost factor.
 An algorithm to recover from the deadlock
Combined Approach to Deadlock Handling
Deadlock detection is the process of actually  Combine the three basic approaches
determining that a deadlock exists and - prevention
identifying the processes and resources - avoidance
involved in the deadlock. - detection
The basic idea is to check allocation against
resource availability for all possible allocation allowing the use of the optimal approach for
sequences to determine if the system is in each of resources in the system.
deadlocked state a. Of course, the deadlock - Partition resources into hierarchically
detection algorithm is only half of this ordered classes.
strategy. Once a deadlock is detected, there - Use most appropriate technique for
needs to be a way to recover several handling deadlocks within each class.
alternatives exists:
 Temporarily prevent resources from
deadlocked processes. DEADLOCK DETECTION
 Back off a process to some check point Allow system to enter deadlock
allowing preemption of a needed resource state then: Detect & Recover.
and restarting the process at the checkpoint
later. Single Instance of Each Resource Type
 Maintain wait-for graph
10  Essentials of Operating System

- Nodes are processes Finish[i]== false AND Requesti  Work


- Pi  Pj if Pi is waiting for Pj If no such i exists, go to step 4
 Periodically invoke an algorithm that
searches for a cycle in the graph. 3. Work = Work + Allocationi
 If there is a cycle, there exists a deadlock Finish[i] = true go to step 2
 An algorithm to detect a cycle in a graph
requires an order of n2 operations, 4. If Finish[i] == false, for some i,
where n is the number of vertices in the 1  i  n, then the system is in deadlock
graph state.

Moreover, if Finish[i] == false, then Pi is


Resource-Allocation Graph and Wait-for deadlocked
Graph
The Algorithm requires m x n2 operations
to detect whether the system is in
deadlocked state

Example of Detection Algorithm


 Five processes P0 through P4;
 Three resource types
A B C

7 2 6

Snapshot at time T0:


Allocation Request Ava
Resource-Allocation ilable
Graph Corresponding wait-for ABC ABC AB
graph C
P0 0 1 0 0 0 0 0
Several Instances of a Resource Type 00
 Available: A vector of length m indicates P1 200 2 0 2
the number of available resources of each P2 303 0 0 0
type. P3 211 1 0 0
 Allocation: An n x m matrix defines the P4 002 0 0 2
number of resources of each type currently
allocated to each process. System is not deadlocked,
 Request: An n x m matrix indicates the sequence <P0, P2, P3, P1, P4> will result
current request of each process. in Finish[i] = true for all i
P2 requests an additional instance of type C
If Request [ij] = k, then process Pi is
Request
requesting k more instances of resource
ABC
type. Rj.
P0 000
P1 201
Detection Algorithm
P2 001
P3 100
1. Let Work and Finish be vectors of
P4 002
length m and n, respectively

Initialize: State of system?


Work = Available
For i = 1,2, …, n, if Allocationi  0, then o Can reclaim resources held by process P0,
Finish[i] = false; otherwise, Finish[i] but insufficient resources to fulfill other
= true processes requests

2. Find an index i such that both: o Deadlock exists, consisting of


processes P1, P2, P3, and P4
Introduction to Operating System  11

without making any progress because they


Recovery from Deadlock: always move the same way at the same time.

 Abort all deadlocked processes


 Abort one process at a time until the
deadlock cycle is eliminated
 In which order should we choose to abort?
- Priority of the process
- How long process has computed,
and how much longer to completion
- Resources the process has used
- Resources process needs to complete
- How many processes will need to be
terminated
- Is process interactive or batch?
 Selecting a victim – minimize cost
 Rollback – return to some safe state,
restart process for that state
 Starvation – same process may always be
picked as victim, include number of rollback
in cost factor

What is a Livelock?
There is a variant of deadlock called livelock.
This is a situation in which two or more
processes continuously change their state in
response to changes in the other process(es)
without doing any useful work. This is similar
to deadlock in that no progress is made but
differs in that neither process is blocked or
waiting for anything.
A human example of livelock would be two
people who meet face-to-face in a corridor
and each moves aside to let the other pass,
but they end up swaying from side to side

Вам также может понравиться