006 Deadlock
006 Deadlock
Note: Some slides and/or pictures in the following are adapted from slides
©2005 Silberschatz, Galvin, and Gagne. Slides courtesy of Anthony D.
Joseph, John Kubiatowicz, AJ Shankar, George Necula, Alex Aiken, Eric
Brewer, Ras Bodik, Ion Stoica, Doug Tygar, and David Wagner.
Goals for Today
• Language Support for Synchronization
• Discussion of Resource Contention and Deadlocks
– Conditions for its occurrence
– Solutions for breaking and avoiding deadlock
Recap: Readers/Writers Problem
W
R
R
R
int Rtn() {
lock.acquire();
…
if (error) {
lock.release();
return errReturnCode;
}
…
lock.release();
return OK;
}
C++ Language Support for Synchronization
• Languages with exceptions like C++
– Languages that support exceptions are more challenging:
exceptions create many new exit paths from the critical section.
– Consider:
void Rtn() {
lock.acquire();
…
DoFoo();
…
lock.release();
}
void DoFoo() {
…
if (exception) throw errException;
…
}
– Notice that an exception in DoFoo() will exit without releasing
the lock
C++ Language Support for Synchronization
(cont’d)
• Must catch all exceptions in critical sections
– Catch exceptions, release lock, and re-throw exception:
void Rtn() {
lock.acquire();
try {
…
DoFoo();
…
} catch (...) { // really three dots!
// catch all exceptions
lock.release(); // release lock
throw; // re-throw unknown
exception
}
lock.release();
}
void DoFoo() {
…
if (exception) throw errException;
…
}
C++ Language Support for Synchronization
(cont’d)
• Alternative (Recommended by Stroustrup): Use the lock class
destructor to release the lock.
• Set it on entry to critical section contained in a { } block, gets
automatically destroyed (& released) on block exit.
• Exceptions will unwind the stack, call destructor, free the lock
• So far: threads:
Execute methods
that modify state
Thread
Wait
Owned A
For
By
Res 1 Res 2
Owned
Wait
Thread By
For B
T1 T2 T3
T1 T2 T3
T1 T3
R3 T4
R3 R2
R4
R4
Simple Resource Allocation Graph Allocation Graph
Allocation Graph With Deadlock With Cycle, but
No Deadlock
Methods for Handling Deadlocks
• Allow system to enter deadlock and then recover
– Requires deadlock detection algorithm (Java JMX
findDeadlockedThreads(), try also jvisualvm)
– Some technique for forcibly preempting resources and/or
terminating tasks
[Avail] = [FreeResources]
Add all nodes to UNFINISHED
do {
done = true
Foreach node in UNFINISHED {
if ([Maxnode]–[Allocnode]<= [Avail]) {
remove node from UNFINISHED
[Avail] = [Avail] + [Allocnode]
done = false
}
}
} until(done)
Banker’s Algorithm Example
• Deadlock preemption
• Deadlock prevention (Banker’s algorithm)