Deadlocks, Livelocks & Starvation
The four Coffman conditions, resource-allocation graphs, prevention, avoidance with the Banker's algorithm (fully worked), detection and recovery, plus livelock, starvation, priority inversion and database deadlocks.
What is a deadlock?
A set of threads is deadlocked when each is waiting for an event (usually the release of a resource) that only another thread in the set can cause. Nobody can proceed — forever.
import threading, time
a, b = threading.Lock(), threading.Lock()
def t1():
with a:
time.sleep(0.1)
with b: # waits for t2 to release b
print("t1 done")
def t2():
with b:
time.sleep(0.1)
with a: # waits for t1 to release a
print("t2 done")
threading.Thread(target=t1).start()
threading.Thread(target=t2).start() # → hangs forever
The four Coffman conditions
All four must hold at once:
| Condition | Meaning | How to break it |
|---|---|---|
| Mutual exclusion | resource can't be shared | make it shareable (read-only data, lock-free structures) — often impossible |
| Hold and wait | hold one, wait for another | request all resources at once; or release everything before requesting more |
| No preemption | can't take a resource away | allow preemption: try-lock with timeout, roll back and retry |
| Circular wait | cycle of waits | impose a global order on resource acquisition |
Resource-allocation graphs
Draw threads as circles and resources as boxes. A request edge T → R means T is waiting for R; an assignment edge R → T means T holds R.
With single-instance resources this collapses to a wait-for graph (T1 → T2 if T1 waits for something T2 holds); a cycle means deadlock.
Strategy 1: Prevention
Lock ordering (breaks circular wait)
The most practical technique. Give every lock a rank and always acquire in increasing rank.
def transfer(src, dst, amount):
first, second = sorted([src, dst], key=lambda acct: acct.id) # global order
with first.lock:
with second.lock:
src.balance -= amount
dst.balance += amount
void transfer(Account from, Account to, long amount) {
Account first = from.id < to.id ? from : to;
Account second = from.id < to.id ? to : from;
synchronized (first) {
synchronized (second) {
from.balance -= amount;
to.balance += amount;
}
}
}
Try-lock and back off (breaks no-preemption / hold-and-wait)
while (true) {
if (a.tryLock(50, TimeUnit.MILLISECONDS)) {
try {
if (b.tryLock(50, TimeUnit.MILLISECONDS)) {
try { doWork(); return; } finally { b.unlock(); }
}
} finally { a.unlock(); }
}
Thread.sleep(ThreadLocalRandom.current().nextInt(10)); // random backoff avoids livelock
}
Strategy 2: Avoidance — the Banker's algorithm
Each process declares its maximum need upfront. Before granting any request, the system checks that it would remain in a safe state.
Worked example
Three resource types with totals A = 10, B = 5, C = 7:
| Process | Allocation (A B C) | Max (A B C) | Need = Max − Alloc |
|---|---|---|---|
| P0 | 0 1 0 | 7 5 3 | 7 4 3 |
| P1 | 2 0 0 | 3 2 2 | 1 2 2 |
| P2 | 3 0 2 | 9 0 2 | 6 0 0 |
| P3 | 2 1 1 | 2 2 2 | 0 1 1 |
| P4 | 0 0 2 | 4 3 3 | 4 3 1 |
Available = total − sum of allocations = (10 − 7, 5 − 2, 7 − 5) = (3, 3, 2).
Safety check — repeatedly pick a process whose Need ≤ Work:
| Step | Pick | Need ≤ Work? | Work after it finishes (Work + Allocation) |
|---|---|---|---|
| start | (3, 3, 2) | ||
| 1 | P1 | (1,2,2) ≤ (3,3,2) ✓ | (5, 3, 2) |
| 2 | P3 | (0,1,1) ≤ (5,3,2) ✓ | (7, 4, 3) |
| 3 | P4 | (4,3,1) ≤ (7,4,3) ✓ | (7, 4, 5) |
| 4 | P0 | (7,4,3) ≤ (7,4,5) ✓ | (7, 5, 5) |
| 5 | P2 | (6,0,0) ≤ (7,5,5) ✓ | (10, 5, 7) |
All finish → safe, with safe sequence ⟨P1, P3, P4, P0, P2⟩.
Request 1: P1 asks for (1, 0, 2). Request ≤ Need(1,2,2) ✓ and ≤ Available(3,3,2) ✓. Pretend to grant: Available = (2,3,0), P1's Allocation = (3,0,2), Need = (0,2,0). The safety check succeeds (P1, P3, P4, P0, P2) → grant.
Request 2 (afterwards): P4 asks for (3, 3, 0). Available is (2,3,0); 3 > 2 → resources not available → P4 waits.
Request 3 (afterwards): P0 asks for (0, 2, 0). Pretend: Available = (2,1,0). Now no process's Need fits (P1 needs B=2, P3 needs C=1, P4 and P2 need A ≥ 4) → unsafe → deny, P0 waits, even though the resources are physically available.
def is_safe(available, allocation, need):
work = available[:]
finish = [False] * len(allocation)
order = []
progressed = True
while progressed:
progressed = False
for i, done in enumerate(finish):
if not done and all(n <= w for n, w in zip(need[i], work)):
work = [w + a for w, a in zip(work, allocation[i])]
finish[i] = True
order.append(i)
progressed = True
return all(finish), order
def request(pid, req, available, allocation, need):
if any(r > n for r, n in zip(req, need[pid])):
raise ValueError("process exceeded its declared maximum")
if any(r > a for r, a in zip(req, available)):
return False # must wait: not available
avail2 = [a - r for a, r in zip(available, req)]
alloc2 = [row[:] for row in allocation]; need2 = [row[:] for row in need]
alloc2[pid] = [a + r for a, r in zip(alloc2[pid], req)]
need2[pid] = [n - r for n, r in zip(need2[pid], req)]
safe, _ = is_safe(avail2, alloc2, need2)
return safe # grant only if still safe
Banker's is rarely used in general-purpose OSes (max needs aren't known, processes come and go), but it's a favourite exam/interview question and its idea — only admit work you can guarantee to finish — reappears in admission control and resource quotas.
Strategy 3: Detection and recovery
Let deadlocks happen, then find and break them.
- Detection: build the wait-for graph and look for cycles (DFS, O(V + E)). With multi-instance resources, run a Banker's-like detection algorithm using current requests instead of max needs.
- When to run: on every wait (cheap with small graphs), periodically, or when CPU utilisation drops suspiciously.
- Recovery:
- abort one or all deadlocked processes (choose the victim by priority, work done, resources held, rollbacks so far — avoid starving the same victim);
- preempt resources and roll back the victim to a checkpoint (databases roll back the transaction).
Strategy 4: Ignore it
Linux, Windows and macOS don't prevent deadlocks between user threads — it's the application's responsibility. The kernel itself uses lock ordering and the lockdep validator to catch violations in testing.
Related liveness problems
| Problem | Threads blocked? | Progress? | Fix |
|---|---|---|---|
| Deadlock | yes, forever | none | ordering, timeouts, detection |
| Livelock | no, busy | none | randomised backoff, tie-breakers |
| Starvation | one thread waits indefinitely | others progress | aging, fair locks/queues |
| Priority inversion | high-prio waits on low-prio | medium-prio runs | priority inheritance / ceiling |
Priority inversion
Deadlocks in databases and distributed systems
- Databases: row/table locks form cycles; the engine detects the cycle, aborts a victim, and the application must retry. Reduce by locking rows in a consistent order (
ORDER BY id … FOR UPDATE), short transactions, and good indexes. - Distributed locks: a holder that crashes or pauses (GC) can hold a lock "forever" — use leases with TTLs and fencing tokens (see Backend concurrency).
- Thread pools: a task that waits for another task submitted to the same bounded pool can deadlock when all workers are waiting (thread-starvation deadlock). Use separate pools or non-blocking composition.
- Microservices: synchronous call cycles (A → B → A) with bounded worker pools can deadlock under load; avoid cycles and always set timeouts.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.