Deadlock, Livelock and Starvation

Topics Covered

What Deadlock Is

The classic example

The four Coffman conditions

Wait for graphs

Deadlock beyond locks

Self deadlock

Deadlock with condition variables and joins

Deadlock versus a slow system

Locks prevent races, but they introduce a new class of failure: threads that stop making progress. The most famous is deadlock, in which a set of threads each wait for a resource held by another thread in the set, so none of them can ever proceed. This section defines deadlock precisely, presents the four conditions that must all hold for it to occur, and shows the resource graph that makes deadlocks visible. The rest of the lesson uses the four conditions as a map of prevention techniques, and then turns to the related failures of livelock and starvation.

The classic example

Two threads transfer money between two accounts, each protected by its own lock. Thread 1 transfers from account A to account B, so it locks A and then B. Thread 2 transfers from B to A, so it locks B and then A. If thread 1 locks A and thread 2 locks B at about the same time, thread 1 then waits for B, held by thread 2, and thread 2 waits for A, held by thread 1. Neither will ever release what it holds, because each is blocked waiting. Both threads, and every other thread that later needs A or B, are stuck forever. The program does not crash and does not use CPU; it simply stops doing work, which is why deadlocks often show up as mysterious hangs rather than errors.

The deadlock happens only under a specific interleaving, both threads taking their first lock before either takes its second. Under light load that window is rare, so the code can pass every test and run for weeks in production before two transfers in opposite directions happen to overlap. This rarity is what makes deadlocks dangerous, and it is why prevention by design is far better than hoping tests will find them.

Each thread holds one lock and waits for the other. Neither can release, so both wait forever, and the program silently stops.

The four Coffman conditions

In 1971, Edward Coffman and colleagues identified four conditions that must all hold simultaneously for a deadlock to occur. Mutual exclusion: at least one resource can be held by only one thread at a time. Hold and wait: a thread holds at least one resource while waiting to acquire another. No preemption: a resource cannot be taken away from the thread holding it; it must be released voluntarily. Circular wait: there is a cycle of threads in which each waits for a resource held by the next.

The value of these conditions is that they are necessary. If any one of them is broken, deadlock is impossible. Every deadlock prevention technique works by removing one condition. Lock free structures remove mutual exclusion. Acquiring all locks at once, or releasing everything before waiting, removes hold and wait. Timeouts with back off, or transactions that can be aborted, simulate preemption. Global lock ordering removes circular wait, and is by far the most widely used technique in practice.

A deadlock needs all four conditions. Each prevention technique removes one of them.

Wait for graphs

Deadlocks are easiest to see as a graph. In a wait for graph, each thread is a node, and an edge from thread T1 to thread T2 means T1 is waiting for a resource that T2 holds. A deadlock exists exactly when the graph contains a cycle. The richer resource allocation graph includes resources as nodes too, with edges from resources to the threads that hold them and from threads to the resources they request; for resources with a single instance, such as locks, a cycle again means deadlock. For resources with several instances, such as a pool of connections, a cycle is necessary but not sufficient, because another instance may become free.

Operating systems, databases and runtime tools use exactly this graph to detect deadlocks. A database lock manager maintains the graph of transactions waiting for row locks and periodically searches it for cycles. The Java virtual machine finds cycles among threads blocked on monitors and reports them in thread dumps. Go detects the special case where every goroutine is blocked and reports all goroutines are asleep, deadlock. Building the graph by hand from a thread dump is also the fastest way to understand a deadlock in production.

Each edge means waits for a lock held by. A cycle is a deadlock. Threads outside the cycle that wait on it are stuck too.

Loading problem...

Deadlock beyond locks

Deadlock is not limited to mutexes. Any resource a thread can hold while waiting for another can participate. Two threads can deadlock on a bounded queue: each waits to put into a queue that only the other drains. A thread pool can deadlock when every worker runs a task that waits for another task submitted to the same pool, which cannot start because no worker is free. A process can deadlock with itself by reading from a pipe whose writer it is also responsible for. Services can deadlock across the network when service A calls service B synchronously while holding a connection from a small pool, and B calls back into A. Async code can deadlock when a coroutine awaits a future that will only be completed by code scheduled after it on a blocked event loop. The four conditions still apply in each case, and so do the remedies.

Self deadlock

The simplest deadlock involves one thread. A thread that tries to acquire a non reentrant mutex it already holds waits for itself forever. This happens when a method that takes a lock calls another method of the same object that also takes it, or when a callback invoked under the lock calls back into the object. Go, C++ std::mutex and Rust Mutex all self deadlock in this case, while reentrant locks in Java and Python allow it. As discussed in the previous lesson, the robust fix is to separate public methods, which take the lock, from private helpers, which assume it is held, so the lock is never taken twice on one path.

Deadlock with condition variables and joins

Waiting primitives other than locks also create deadlocks that are easy to overlook. A thread that waits on a condition variable for a signal that will only be sent by a thread blocked on the mutex the waiter forgot to release is stuck forever, and a thread that joins another thread while holding a lock that the other thread needs before it can exit deadlocks just as surely as two mutexes. Shutdown code is a frequent offender: a main thread holds a registry lock while joining workers, and each worker needs that registry lock to deregister itself on exit. The rule generalizes the one for locks: never wait for another thread, through a join, a future, a latch or a queue, while holding a lock that thread may need to finish.

Deadlock versus a slow system

Not every hang is a deadlock. A thread waiting for a slow disk, a network call without a timeout, or a lock held by a thread doing a long computation looks similar from the outside. The distinguishing feature is that a deadlock never resolves by itself, while a slow wait eventually completes. Taking several thread dumps over a minute separates the two: in a slow system, the holder of the contended resource is running and its stack changes; in a deadlock, every thread in the cycle stays blocked at exactly the same frame. Knowing which case you are in avoids wasting time searching for a lock cycle when the real problem is a missing timeout on an external call.

Deadlock is a cycle of waiting

A deadlock requires mutual exclusion, hold and wait, no preemption and circular wait all at once. It shows up as a hang, not an error, and appears only under rare interleavings, so prevent it by design. Drawing the wait for graph from a thread dump is the fastest way to understand one that already happened.