Deadlock and How to Handle It
Learn the four conditions for deadlock, read resource allocation graphs, and compare prevention by lock ordering, avoidance, and detection and recovery.
Welcome back!
Step 1 of 13Learn
Four cars, one intersection
Four cars arrive at a four-way intersection at the same moment. Each pulls halfway in and waits for the car on its right to move. None can move. Unless someone backs up, they will wait forever.
That's a deadlock: a set of threads or processes, each waiting for a resource held by another member of the set, so none can ever proceed.
In software it typically looks like this. Thread 1 locks the accounts mutex, then tries to lock the audit log mutex. At the same moment, thread 2 locks the audit log, then tries to lock accounts. Each holds what the other needs. Both wait. The program doesn't crash and doesn't use any CPU; it simply stops making progress, which can be harder to diagnose than a crash.
Deadlock is different from two related problems:
- Starvation: a thread could proceed in principle but keeps losing out, for example to higher-priority threads.
- Livelock: threads keep changing state in response to each other without making progress, like two people in a hallway who both step left, then both step right, again and again.
The Mars Pathfinder lander in 1997 suffered repeated system resets due to a related problem called priority inversion; engineers diagnosed it remotely and fixed it by changing a setting from Earth. Concurrency bugs reach far.
Step 2 of 13Learn
The four necessary conditions
In 1971, Coffman and colleagues showed that a deadlock can arise only if all four of these conditions hold at once:
- 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: resources can't be forcibly taken away; a thread releases them only voluntarily.
- Circular wait: there is a cycle of threads, T1 waiting for T2, T2 for T3, and so on, back to T1.
The power of this list is that breaking any one condition makes deadlock impossible. That gives four strategies for prevention:
- Make resources shareable where possible, such as read-only files, to break mutual exclusion.
- Require threads to request all resources at once, or release everything before asking for more, to break hold and wait.
- Allow the system to take resources back, such as rolling back a database transaction, to break no preemption.
- Impose a global order on resources and always acquire them in that order, to break circular wait.
The last one is the most widely used in practice. If every thread that needs both accounts and audit log must lock accounts first, a cycle can't form.
Step 3 of 13Diagram
All four must hold for deadlock
Remove any one part and deadlock cannot happen. Tap each condition.
Tap a shape with to see more.
- Deadlock
- Mutual exclusion
A resource can be held by one thread at a time.
- Hold and wait
Holding one resource while waiting for another.
- No preemption
Resources are released only voluntarily.
- Circular wait
A cycle of threads each waiting for the next. Always locking in one global order breaks it.
Step 4 of 13Practice · Match the pairs
Match each prevention technique to the deadlock condition it breaks.
Tap an answer, then tap the place where it belongs (or drag it there).
- Always lock resources in a fixed global order
- Request every needed lock at once, or none
- Let the system roll back a transaction and take its locks
- Use read-only data that any number of threads can share
Step 5 of 13Learn
Resource allocation graphs
A resource allocation graph shows who holds what and who wants what. Threads are drawn as circles and resources as squares.
- An arrow from a resource to a thread means the thread holds it.
- An arrow from a thread to a resource means the thread is waiting for it.
Example: R1 → T1 (T1 holds R1), T1 → R2 (T1 wants R2), R2 → T2 (T2 holds R2), T2 → R1 (T2 wants R1). Follow the arrows: T1 → R2 → T2 → R1 → T1. That's a cycle, so T1 and T2 are deadlocked.
When each resource has exactly one instance, as with mutexes, a cycle in the graph means deadlock. When resources have several identical instances, such as 3 printers, a cycle means deadlock is possible but not certain, because another thread might release an instance and break the wait.
Operating systems and databases use this idea in deadlock detection: periodically build the waits-for graph and search for cycles. Databases do this constantly. When two transactions deadlock, the database picks one as the victim, aborts it and releases its locks, and the application retries it. Linux includes a debugging tool called lockdep that records the order in which kernel locks are taken and warns as soon as code acquires them in an order that could ever form a cycle.
Step 6 of 13Diagram
The cycle in the example graph
Tap a shape with to see more.
- T1
Holds R1, wants R2.
- R2
Held by T2.
- T2
Holds R2, wants R1.
- R1
Held by T1.
Step 7 of 13Practice · What would you do?
What would you do?
Thread A holds lock L1 and is waiting for L2. Thread B holds L2 and is waiting for L3. Thread C holds L3 and is waiting for nothing; it is busy computing and will release L3 in a moment. Each lock has one instance. Is the system deadlocked?
Step 8 of 13Learn
Avoidance, detection, or ignoring it
Besides prevention, there are three broader strategies.
Avoidance lets the system grant a request only if the result is a safe state: one where there exists some order in which every thread can still get its maximum needs and finish. The best-known method is Dijkstra's banker's algorithm, which works like a cautious bank that only lends if it can still satisfy every customer's maximum credit line in some order. It requires each thread to declare its maximum needs in advance and adds work to every request, so general-purpose operating systems rarely use it.
Detection and recovery lets deadlocks happen, finds them by searching for cycles, then recovers by aborting a victim or rolling back its work. Databases rely heavily on this because transactions can be safely rolled back and retried.
Ignoring the problem, sometimes called the ostrich approach, is what most general-purpose operating systems do for application-level locks. The kernel carefully avoids deadlocks in its own code, but if two of your threads deadlock on your own mutexes, the OS won't intervene; you'll see a frozen program and need to kill it. The reasoning is cost: checking every lock operation for deadlock would slow everything, while deadlocks in well-written programs are rare.
For programmers, the practical defenses are lock ordering, holding as few locks as possible, using timeouts on lock attempts, and preferring higher-level concurrency tools.
Step 9 of 13Compare
Four strategies for deadlock
| Aspect | Prevention | Avoidance | Detection and recovery | Ignore it |
|---|---|---|---|---|
| Idea | Break one of the four conditions | Grant only requests that stay safe | Let it happen, find cycles, break them | Assume it is rare; reboot or kill if needed |
| Example | Global lock ordering | Banker's algorithm | Databases aborting a transaction | Most desktop OS kernels for app locks |
| Cost | Design constraints | Must know max needs; slow checks | Lost work in the victim | Occasional hangs |
Step 10 of 13Try the calculator
Banker's check for one resource type
A system has a fixed number of identical resource units. Thread X still needs (max − held) more units. Is it safe to let X finish first?
- Available units
- 2
- Units missing (0 means X can finish now)
- 1
Step 11 of 13Practice · Put in order
Order the steps of a database's deadlock detection and recovery.
Drag the items, or use the arrow buttons, to put them in order.
- It finds a cycle in the graph
- Transactions acquire row locks and some begin waiting
- The victim's locks are released and the others continue
- It chooses a victim transaction and aborts it
- The application retries the aborted transaction
- The database builds a graph of which transaction waits for which
Step 12 of 13Note
Step 13 of 13Practice · Choose one
Two functions in a program both lock mutex M1 and mutex M2. Function f locks M1 then M2; function g locks M2 then M1. Occasionally the program freezes. What is the simplest reliable fix?
Lesson complete!