walked through 3-way join solution
discussed deadlock
Deadlock occurs when a system is unable to make progress because threads are blocking each other.
Consider the "dining philosophers" problem: n philosophers are sitting around a table, wanting to eat. Between each pair of philosophers is a single chopstick; a philosopher needs two chopsticks to eat. One possible way to write the pseudocode for each philosopher:
while hungry: pick up left chopstick (blocking if unavailable) pick up right chopstick (blocking if unavailable) eat set down left chopstick set down right chopstick |
This solution may exhibit deadlock if all threads pick up their left chopstick before any thread picks up the right chopstick. At that point, all of the philosophers are waiting for a chopstick, but no chopstick is available, so the system is deadlocked.
The following conditions are necessary and sufficient for a system to be in deadlock: - mutual exclusion: multiple threads cannot simultaneously hold the same resource
hold and wait: threads can hold one resource while waiting for another
no preemption: it is impossible to force a thread to relinquish a resource until it has completed its task
circular wait: there is a thread that is currently waiting for another thread, which is currently waiting for another thread, ..., which is currently waiting on the first thread.
The circular wait condition can be easily explained using a resource allocation graph. The graph is drawn according to the following rules:
vertices represent either threads (drawn as ovals) or resources (drawn as rectangles).
an edge from a thread to a resource indicates that the thread is waiting to acquire the resource
an edge from a resource to a thread indicates that the thread is holding the resource
Assuming mutual exclusion, no preemption, and hold and wait, the system is deadlocked if and only if there is a (directed) cycle in the resource allocation graph. Here is the graph for the deadlocked dining philosophers scenario described above:
Here each philosopher is holding the chopstick on her left, while trying to acquire the chopstick on her right.
There are a few strategies for mitigating deadlock, which are discussed in more detail in the next lecture.