Definition
A deadlock is a state in which each of a set of threads (flows of execution in a program) waits for an event that only a member of the set can cause, so none ever proceeds. The event is usually the release of a resource such as a mutex §9.5, a lock one thread at a time may hold, but can be any event, such as a message or a function’s return. The deadlock lasts until something outside the set intervenes. In starvation §9.18, by contrast, other threads keep progressing.
The idea
Two threads each need two mutexes, X and Y. Thread A locks X, then Y. Thread B locks Y, then X. Usually one thread finishes before the other starts, and nothing goes wrong. But if A locks X and, before A reaches Y, B locks Y, then A waits for Y, which B holds, and B waits for X, which A holds. Each could release its mutex only by continuing, and neither can continue. No error is reported, no processor time is used, and the two threads wait forever. The bad interleaving needs particular timing, so the program may pass every test and deadlock only rarely in use.
Traffic gridlock is the classic picture: four cars reach a four-way crossing at the same moment, each must let the car on its right go first, and so none moves. Each car keeps the road it stands on while waiting for the road ahead, exactly as a thread keeps its mutex. The picture stops where drivers can wave each other on or reverse; a thread blocked on a mutex has no such option unless its programmer gave it one, such as a timeout §9.34.
How it works
Coffman, Elphick and Shoshani showed in 1971 that a deadlock over resources needs four conditions at once [297]:
Mutual exclusion: a resource can be held by at most one thread at a time.
Hold and wait: a thread keeps the resources it holds while it waits for another.
No preemption: a resource cannot be taken away from its holder; only the holder releases it.
Circular wait: there is a cycle of threads, each waiting for a resource that the next thread in the cycle holds.
The first three are properties of the resources and of the locking rules. The fourth is what actually happens at run time. Removing any one of the four prevents deadlock.
To find a deadlock, draw a wait-for graph: one node for each thread, and an arrow from thread to thread whenever waits for something that holds or must do. When every resource has a single instance, a deadlock exists exactly when the arrows form a closed cycle. In the example above, A waits for Y, held by B, which gives an arrow from A to B; B waits for X, held by A, which gives an arrow from B to A. The two arrows form a cycle of length 2.
Arrows come from every kind of wait, not only from mutexes:
A thread that holds a lock and calls a callback §14.22, a function that other code supplied to be called later, waits for that callback to return; if the callback takes the same lock, the thread waits for itself, a cycle of length 1.
A thread that waits for a message or a signal waits for the thread that would send it.
A job on a work queue §6.36, a list of jobs that one worker thread runs one after another, that waits for a second job queued on the same worker makes the worker wait for itself, because the second job cannot start until the first returns.
On a single-core processor, an interrupt handler §6.12 that waits for a lock held by the code it interrupted waits forever, because the interrupted code cannot run until the handler returns.
There are four ways to handle deadlock:
Prevention removes one of the four conditions by design. Lock ordering §9.15 removes circular wait: every thread takes locks in one fixed order. Taking every needed lock in one step removes hold and wait. Giving up held locks when the next one is unavailable, called try-lock and back off, removes the no-preemption condition.
Avoidance grants a request only if every thread can still finish afterwards, given each thread’s declared maximum needs; Dijkstra’s banker’s algorithm §14.1 is the standard method. Programs rarely know their maximum needs in advance.
Detection and recovery finds cycles in the wait-for graph at run time and breaks one by stopping a thread or undoing its work. Many database systems abort one transaction §8.7 (a group of changes applied completely or not at all) in the cycle and report an error, so that the transaction can be run again.
Restart accepts that deadlock may happen and resets the system when it hangs, for example through a watchdog timer §6.16, a hardware timer that resets the processor unless software restarts the timer regularly.
Worked example
Two threads and two mutexes, each with one instance; times are in milliseconds.
At 0 ms, A locks X. At 1 ms, B locks Y.
At 2 ms, A requests Y. B holds Y, so A blocks. The graph has the arrow A B.
At 3 ms, B requests X. A holds X, so B blocks. The graph gains the arrow B A, and the cycle is closed.
From 3 ms on, both threads are blocked. The only instructions that could release X or Y are later instructions of A and B themselves, and those never run. Had B started after A had released both mutexes, the same code would have run without waiting: whether it deadlocks depends only on timing.
A deadlock inside one thread: a thread calls a function update, which locks a mutex M that does not allow its holder to lock it again, and then calls a callback that another module registered. The callback calls update again to change a setting. That inner call tries to lock M. M is held by the same thread, which is waiting for the callback to return, so the thread waits for itself: a graph with one node and one arrow from the node to itself. A recursive mutex, which lets its holder lock it again and counts the locks, removes this wait. The inner update then runs while the outer one is half done, and it can read or damage half-updated data.
A cycle proves deadlock only when every resource has one instance. Take a pool of 2 identical buffers handed out by a counting semaphore §9.6, a counter of free units that threads take and give back. Thread C holds 1 buffer and waits for mutex X. Thread D holds X and waits for a buffer. Thread E holds the other buffer and is running. C waits for D, and D waits for C or E, so the graph has a cycle between C and D. Yet when E returns its buffer, D takes it, finishes and releases X, and C proceeds: D’s wait was satisfied from outside the cycle.
Stated precisely
Let be the wait-for graph at one moment: a node for each thread, and an arrow when thread is blocked until thread releases a resource or causes an event. Assume three things.
Every resource has exactly one instance.
A held resource is released only by its holder, and only when the holder runs: nothing takes a resource away.
A blocked thread does nothing until the event it waits for happens: no timeout and no other event wakes it.
Under these assumptions the threads on a cycle of are deadlocked, and so is every thread that has a path of arrows leading into a cycle. Conversely, if has no cycle, no thread is deadlocked at that moment: every chain of arrows ends at a thread that is not blocked and can still run.
When a resource has several instances, a thread may wait for any one of several holders, and a cycle is necessary but not sufficient for deadlock, as the buffer example shows. Deadlock violates a liveness property §1.12, a requirement that something good eventually happens: here, that every waiting thread eventually gets what it waits for.
Limits and common mistakes
A timeout ends a wait but does not repair anything. The thread that gave up must release what it holds and undo half-done work. If both threads give up, release and retry with the same timing, they can collide again and again. Threads that keep running but make no progress are in a livelock. Random delays before each retry break the symmetry.
Tests cannot show that deadlock is impossible, because the dangerous interleaving may need timing that no test produced. Show instead that no cycle can form, for example through lock ordering, or use a tool that checks the order of lock acquisitions on every run, such as the Linux kernel’s lockdep, which reports a possible deadlock even in a run that did not deadlock.
Priority does not help. A blocked thread cannot run whatever its priority, so raising the priority of deadlocked threads, which is what priority inheritance §9.17 does, changes nothing.
A recursive mutex prevents only the one-thread wait on itself, and it hides the real problem: the re-entering code runs inside an unfinished update.
Questions answered
Which wait-for cycle can occur when a callback reenters the update path?
The cycle that can occur is this: the update code holds a lock while it runs the callback, and the callback calls back into the update code, which then waits for the same lock. The update path is the code that changes some shared state while holding that lock, and the callback reenters it when it calls that code again before the first call has returned. The outer call cannot release the lock until the callback returns, and the callback cannot return until it gets the lock. When both run on one thread and the lock does not allow its holder to lock it again, the thread waits for itself: a cycle with one thread and one arrow.
Two variants have the same shape across threads. In the first, the update code holds the lock and waits for the callback to finish on another thread, such as a worker thread, while the callback waits for the lock: the caller waits for the worker, and the worker waits for the caller. In the second, the update code runs as a job on a single worker thread and waits for another job queued behind it on the same worker, which cannot start until the first job returns.
The usual repairs are to call code you do not control only after releasing the lock (copy what the callback needs first), to queue the reentrant request so that it runs after the lock is released, or to detect the re-entry and reject it with an error. A recursive lock, which lets its holder lock it again, removes the wait, but the callback then runs on half-updated state.
Related entries: Lock ordering (§9.15), Reentrancy (§9.27), Cancellation (§9.29), Starvation (§9.18), Mutex (§9.5), Liveness property (§1.12). Further reading: [297].