Section 9.14

Deadlock

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]:

  1. Mutual exclusion: a resource can be held by at most one thread at a time.

  2. Hold and wait: a thread keeps the resources it holds while it waits for another.

  3. No preemption: a resource cannot be taken away from its holder; only the holder releases it.

  4. 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 TT to thread UU whenever TT waits for something that UU 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:

There are four ways to handle deadlock:

Worked example

Two threads and two mutexes, each with one instance; times are in milliseconds.

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 GG be the wait-for graph at one moment: a node for each thread, and an arrow T→UT \to U when thread TT is blocked until thread UU releases a resource or causes an event. Assume three things.

  1. Every resource has exactly one instance.

  2. A held resource is released only by its holder, and only when the holder runs: nothing takes a resource away.

  3. 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 GG are deadlocked, and so is every thread that has a path of arrows leading into a cycle. Conversely, if GG 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].