09 Deadlock
09 Deadlock
Lecture 9: Deadlock
Outline
• Definitions
• Four conditions for deadlocks
• Mutual exclusion
• Hold and wait
• No preemption
• Circular wait
• Techniques for addressing Deadlock
Starvation vs. Deadlock
Resource 1 Resource 2
Thread B
Waiting for Owned by
• Mutual exclusion
• Only limited number of threads at a time can use resource
• Hold and wait
• Thread hold resources while waiting to acquire additional ones
• No preemption
• Resources are released only voluntarily by thread holding them
• Circular wait
• There exists a set T1, …, Tn of waiting threads
• T1 is waiting for resource that is held by T2
• T2 is waiting for resource that is held by T3
• …
• Tn is waiting for resource that is held by T1
Resource Allocation Graph
• System model
Symbols
• Threads T1, T2, . . ., Tn T1 T2
• Resource types R1, R2, . . ., Rm
• CPU cycles, memory space, I/O devices
• Each resource type Ri has Wij instances
R1
• Each thread utilizes resources as follows
R2
• Request() / Use() / Release()
R1 R2
R1 R2 R1
T2
T1 T2 T3
T1 T2 T3
T1 T3
R3 T4
R3 R2
R4
R4
Di y R
sal ule
B
low
ed
Methods for Handling Deadlocks
• If there is only one unit of each type of resource Þ look for loops
• More general deadlock detection algorithm
• Let [x] represent m-ary vector of non-negative integers (units per type)
[FreeResources]: Current free resources each type
[Requesti]: Current requests from thread i
[Alloci]: Current resources held by thread i
• See if tasks can eventually terminate on their own
[Avail] = [FreeResources]
Add all nodes to UNFINISHED R1
T2
do {
done = true
foreach node in UNFINISHED {
if ([Requestnode] <= [Avail]) { T1 T3
remove node from UNFINISHED
[Avail] = [Avail] + [Allocnode]
done = false
}
} R2 T4
} until(done)
R1 R2
T1 T2 T3 T4
R3
Techniques for Preventing Deadlock
• Infinite resources
• Include enough resources so that no one ever runs out of resources
• Doesn’t have to be infinite, just large
• Give illusion of infinite resources (e.g. virtual memory)
• Examples:
• Bay bridge with 12,000 lanes. Never wait!
• Infinite disk space (not realistic yet?)
• Force all threads to request resources in fixed order preventing any cyclic
use of resources
• Thus, preventing deadlock
• Example (x.P, y.P, z.P,…)
• Make tasks request disk, then memory, then…
• Keep from deadlock on freeways by requiring everyone to go clockwise
Banker’s Algorithm
• Really conservative!
Banker’s Algorithm (cont.)
• Also Slow/Impractical
• Matrix of resources/requirements could be big and dynamic
• Re-evaluate on every request (even for small/non-contended)
• Banker’s algorithm assumes everyone asks for max
• REALITY
• Most OSs don’t bother
• Programmers job to write deadlock-free programs
(e.g. by ordering all resource requests).
Summary
globaldigitalcitizen.org
Acknowledgment