You are on page 1of 79

What is Deadlock?

• Process Deadlock
• A process is deadlocked when it is waiting on
an event which will never happen

• System Deadlock
• A system is deadlocked when one or more
processes are deadlocked
The Deadlock: How it happens?
A Computing example:
• Scanned document to be Recorded on CD
• System has 1 scanner and 1 CD Recorder
• 2 processes each need both devices.
P0 acquires scanner and waits for CD
P1 acquires CD and waits for scanner
P0 will not release scanner until catch hold the CD
P1 will not release CD until catch hold the scanner
Result: Deadlock
Preemptable and Non Preemptable Resources
Things for which we request exclusive access.
Examples: Databases, files, shared memory,
printer, cd/dvd writer, tape drive, etc.
Types
1. Preemptable – can be taken away w/out ill
effects
2. Non preemptable – cannot be take away
w/out causing a failure!
Resource examples
• Memory – preemptable
• CPU – preemptable
• CD writing – non preemptable
• Printing – non preemptable

We will only consider non preemptable (the


harder problem).
Deadlock caused by Nonpreemptable Resources
Sequence of events required to use a resource:
1. Request the resource.
2. Use the resource.
3. Release the resource.
Introduction To Deadlocks

Deadlock can be defined formally as follows:


• A set of processes is deadlocked if each process in the
set is waiting for an event that only another process
in the set can cause.
Conditions for Resource Deadlocks
The following four conditions are necessary for a
deadlock to occur:
1. Mutual exclusion condition
2. Hold and wait condition.
3. No preemption condition.
4. Circular wait condition.
Resource Allocation Graphs

Process A

Resource R

Request a Resource A R
A

Hold a Resource A R
R S
Deadlock
B
Deadlock Modeling (1)
Process Resource

• Resource allocation graphs.


(a) Process A Holding a resource R.
(b) Process B Requesting a resource S.
(c) Deadlock for resources T & U among Process C & D
Deadlock Modeling (2)

• An example of how deadlock occurs and how it can


be avoided.
Deadlock Modeling

• An example of how deadlock occurs and how it can be


avoided.
Deadlock Modeling

• An example of how deadlock occurs and how it can be


avoided.
Deadlock Detection with
One Resource of Each Type

•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.

(a) A resource graph.


(b) A cycle extracted from (a).
Deadlock Detection with One Resource of Each Type
Algorithm for detecting deadlock:
1. For each node, N in the graph, perform the following five steps
with N as the starting node.
2. Initialize L to the empty list, designate all arcs as unmarked.
3. Add current node to end of L, check to see if node now appears in
L two times. If it does, graph contains a cycle (listed in L),
algorithm terminates.
4. From given node, see if any unmarked outgoing arcs. If so, go to
step 5; if not, go to step 6.
5. Pick an unmarked outgoing arc at random and mark it. Then
follow it to the new current node and go to step 3.
6. If this is initial node, graph does not contain any cycles, algorithm
terminates. Otherwise, dead end. Remove it, go back to previous
node, make that one current node, go to step 3.
(Directed) Graphs
• A graph G = (V,E) where
V = vertex set and
E = edge set
• Ordered pairs of vertices
• Ex. Let G = (V,E) where
V = { C, D, T, U } and
E = { <D,U>, <U,C>, <C,T>, <T,D> }
Deadlock Dealing Strategies
Strategies for dealing with deadlocks:
1. Just ignore the problem.
2. Detection and recovery. Let deadlocks occur, detect
them, take action.
3. Dynamic avoidance by careful resource allocation.
4. Prevention, by structurally negating one of the four
required conditions.
Ignore the Problem: Ostrich Problem

• May not occur very often


• May not have serious consequences if it does happen
• May be difficult / expensive to detect.
Ostrich algorithm

Ignore it; pretend it doesn’t


happen! 18
Ways of Handling Deadlock

• Deadlock Detection
• Deadlock Recovery
• Deadlock Avoidance
• Deadlock Prevention
2. Detect and recover

1. Detection with one resource of each type


2. Detection with multiple resources of each
type
Detection with one resource of each type
Detect cycle in digraph
• For each vertex v in graph,
• search the sub tree rooted at v
• see if we visit any vertex twice (by keeping a
record of already visited vertices).
T
Deadlock Detection with Multiple Resources

Four data structures used by the deadlock detection algo.


• i denote type of resources in Ei and Ai
• Ei and Ai denote the number of resources of type i
• Example, if class 1 is tape drives, then E1 = 2 means the
system has two tape drives.
Deadlock Detection with Multiple Resources

Deadlock detection algorithm:


1. Look for an unmarked process, Pi , for which the i-th
row of R is less than or equal to A.
2. If such a process is found, add the i-th row of C to A,
mark the process, and go back to step 1.
3. If no such process exists, the algorithm terminates.
Deadlock Detection with Multiple Resources

An example for the deadlock detection algorithm.


Recovery

1. Preemption
2. Rollback (using checkpoints)
3. Kill process
Recovery: preemption
• Temporarily take back needed resource
• Ex. Printer
• Pause at end of page k
• Start printing other job
• Resume printing original job starting at page k+1
Recovery: Rollback
• Checkpoint – save entire process state (typically right
before the resource was allocated)

• When deadlock is detected, we kill the check pointed


process, freeing the resource, and then later restart
the killed process starting at the checkpoint.
• Requires apps that can be restarted in this
manner.
Rdb’s & commit/rollback

From p. 62, http://www.postgresql.org/files/documentation/pdf/8.0/postgresql-8.0-US.pdf


Recovery: kill process

• Requires apps that can be restarted from the


beginning.
Deadlock Avoidance

• Allow the chance of deadlock to occur, but avoid it


happening when it is going to happen!!!
• Check whether the next state (change in system) may
end up in a deadlock situation; avoid it.
• Plotting of Graph (Next Slide) Explains the idea!!!
Deadlock Avoidance

• Two process resource trajectories.


Deadlock avoidance
• Safe state = NO deadlock! there exists some
scheduling order in which every process can
run to completion even if all of them suddenly
request their max number of resources
immediately

• Unsafe != deadlocked
Safe states
Unsafe states

With only 4 free, neither A nor C can


be completely satisfied.
Ways of Handling Deadlock
• Deadlock Avoidance
• Deadlock Prevention
Deadlock Avoidance

• Allow the chance of deadlock to occur, but avoid it


happening when it is going to happen!!!
• Check whether the next state (change in system) may
end up in a deadlock situation; avoid it.
• Plotting of Graph (Next Slide) Explains the idea!!!
Deadlock Avoidance

• Two process resource trajectories.


Deadlock avoidance
• Safe state = NO deadlock! there exists some
scheduling order in which every process can
run to completion even if all of them suddenly
request their max number of resources
immediately

• Unsafe != deadlocked
Safe states
Unsafe states

With only 4 free, neither A nor C can


be completely satisfied.
BANKER’S ALGORITHM FOR SINGLE
RESOURCE (SR) TYPE
Dijkstra's Banker's Algorithm
Definitions
• Each process has a LOAN, MAXIMUM NEED, CLAIM
• LOAN: current number of resources held
• MAXIMUM NEED: total number resources
needed to complete
• CLAIM: = (MAXIMUM - LOAN)
Assumptions
• Establish a LOAN ceiling (MAXIMUM NEED) for each
process
• MAXIMUM NEED < total number of resources
available (ie., capital)
• Total loans for a process must be less than or equal to
MAXIMUM NEED
• Loaned resources must be returned back in finite
time; Assume immediately after completion.
• Total resources available are much less than the total
committed accumulative resources .
Algorithm
1. Search for a process with a claim that can be
satisfied using the current number of remaining
resources (ie., tentatively grant the claim)
2. If such a process is found then assume that it
will return all the loaned resources.
3. Update the number of remaining resources
4. Repeat steps 1-3 for all processes and mark
them completed.
• DO NOT GRANT THE CLAIM if at least one process
can not be marked to completion.

Implementation
• A resource request is only allowed if it results in a
SAFE state
• The system is always maintained in a SAFE state
so eventually all requests will be filled
Advantages
• It works
• Allows jobs to proceed where a prevention
algorithm wouldn't
Problems
• Requires that there are a fixed number of
resources
• What happens if a resource goes down?
• Does not allow the process to change its
Maximum need while processing
Banker’s algorithm (SR)

• Grant only those requests that lead to safe states.


• Requires future information.
Banker’s algorithm (SR)

Issue2 get back 4


Free =4

• (b) is safe because from (b) we can give C 2 more


(free=0) then C completes (free=4) then give
either B or D . . .
Banker’s algorithm (SR)

Issue 1 to B
Free =1
No max could be
served now

• (c) is unsafe because no max can be satisfied


BANKER’S ALGORITHM FOR MULTIPLE
RESOURCE (MR) TYPES
Banker’s algorithm (MR)

N:
(need)

E=existing (total); constant



P=possessed (allocated/held)
A=available (free)
Banker’s algorithm (MR)
To check for a safe state:
1. Look for a row, R, in N <= A.
2. Assume the chosen process of
the row requests all resources,
runs to completion, and
terminates (giving back all of
its resources to A).
3. Repeat steps 1 and 2 until
either all processes run to
completion or terminate
(indicating that the initial state
is safe) or deadlock occurs.
Banker’s algorithm (MR)

To check for a safe state:


1. Look for a row, R, in N <= A.

A (available)
can
completely
satisfy D’s
needs.
Banker’s algorithm (MR)
Previous:
E=(6342)
To check for a safe state:
P=(5322)
1. Look for a row, R, in N <= A.
A=(1020)
2. Assume the process of the chosen row requests all
resources, runs to completion, and terminates
(giving back all of its resources to A).

After D
terminates:
E=(6342)
P=(4221)
A=(2121)
Banker’s algorithm (MR)
Previous:
E=(6342)
To check for a safe state:
P=(5322)
1. Look for a row, R, in N <= A. A=(1020)

E=(6342)
P=(4221)
A=(2121)
Banker’s algorithm (MR)
Previous:
E=(6342)
To check for a safe state:
P=(4221)
1. Look for a row, R, in N <= A.
A=(2121)
2. Assume the process of the chosen row requests all
resources, runs to completion, and terminates
(giving back all of its resources

After A
terminates:
E=(6342)
P=(1210)
A=(5132)
Banker’s algorithm (MR)
Previous:
E=(6342)
To check for a safe state:
P=(4221)
1. Look for a row, R, in N <= A.
A=(2121)

E=(6342)
P=(1210)
A=(5132)
Banker’s algorithm (MR)
Previous:
E=(6342)
To check for a safe state:
P=(1210)
1. Look for a row, R, in N <= A.
A=(5132)

E=(6342)
P=(1110)
A=(5232)
Banker’s algorithm (MR)
Previous:
E=(6342)
To check for a safe state:
P=(1210)
1. Look for a row, R, in N <= A.
A=(5132)

E=(6342)
P=(1110)
A=(5232)
DEADLOCK PREVENTION
Deadlock Prevention

• Remove the possibility of deadlock occurring by


denying one of the four necessary conditions:
• Mutual Exclusion (Can we share everything?)
• Hold & Wait
• No preemption
• Circular Wait
Deadlock prevention: Attack mutex

• Example: Use spooling instead of mutex on printer


• Not all problems lend themselves to spooling
• Still have contention for disk space with spooling
Deadlock prevention: attack hold & wait
• Request (and wait for) all resources prior to process
execution
Problems:
• We may not know in advance the requirements
of resources.
• We tie up resources for entire time.
• Before requesting a resource, we must first
temporarily release all allocated resources and then
try to acquire all of them again.
Denying the “Hold & Wait”

Implementation
• A process is given its resources on a "ALL or
NONE" basis
• Either a process gets ALL its required
resources and proceeds or it gets NONE of
them and waits until it can
Denying the “Hold & Wait”
Advantages
• It works
• Reasonably easy to code

Problems
• Resource wastage
• Possibility of starvation
Denying “No pre-emption”

• Tricky at best.
• Impossible at worst.
Implementation
• Resources may be removed from a process
before it is finished with them. Forcefully
preempt the resource.
Denying “No pre-emption”
Advantages
• It works
• Possibly better resource utilisation
Problems
• The cost of removing a process's resources
• The process is likely to lose work it has done.
(How often does this occur?)
• Possibility of starvation
Attacking the Circular Wait Condition

(a) Numerically ordered resources. (b) A resource graph.

• Processes can request resources whenever they want


to, but all requests must be made in numerical order.
• Example: A process may request first a printer and
then a tape drive, but it may not request first a plotter
and then a printer.
Deadlock prevention: attack circular wait
1. Only allow one resource at a time.
2. Request all resources in (some globally assigned)
numerical order.
• But no numerical ordering may exist!
Implementation
• Resources are uniquely numbered
• Processes can only request resources in linear
ascending order
• Thus preventing the circular wait from occurring
Deadlock prevention: attack circular wait
Advantages
• It works
• Has been implemented in some OS
Problems
• Resources must be requested in ascending
order of resource number rather than as
needed
• Resource numbering must be maintained by
someone and must reflect every addition to
the OS
• Difficult to sit down and write just write code
Approaches to Deadlock Prevention

Summary of approaches to deadlock prevention.


Other Issues
• Two-phase locking
• Commonly used in databases.
• First phase: lock all the needed resources. If
locking succeeds, go to second phase, else
release all the locks.
• Second phase: do the read or write operation.
• Communication deadlocks
• Livelock
• Starvation
Two-phase locking
Two-phase locking
• Commonly used in databases.
• First phase: lock all the needed resources. If
locking succeeds, go to second phase, else
release all the locks; go to First Phase.
• Second phase: do the read or write operation.
And release the records
Communication Deadlocks
Example:
• Suppose process A sends a request message to process
B, and then blocks until B sends back a reply message.
• Suppose that the request message gets lost. A is blocked
waiting for the reply.
• B is blocked waiting for a request asking it to do
something.
• We have a deadlock! Not the classical resource
deadlock. This situation is called a communication
deadlock.
Communication Deadlocks

• In a communication system a node is either computer or


Router having finite buffers ( 8 in example)
• If no buffer available we have a resource deadlock in a
network.
Communication Deadlocks
Example:
• Suppose that all the packets at router A need to go to
B and all the packets at B need to go to C and all the
packets at C need to go to D and all the packets at D
need to go to A.
• No packet can move because there is no buffer at the
other end and we have a classical resource deadlock,
in the middle of a communications system.
Livelock

• Busy waiting that can lead to livelock.


Livelock
Example:
• In some situations, polling (busy waiting) is used to
enter a critical region or access a resource. This
strategy is often used when the mutual exclusion will
be used for a very short time and the overhead of
suspension is large compared to doing the work.
• Consider an atomic primitive in which the calling
process tests a mutex and either grabs it or returns fail.
• We do not have a deadlock (because no process is
blocked) but we have functionally equivalent to
deadlock but livelock.

You might also like