Deadlocks and lock order
hard 65 minTwo threads, two locks, and a program that waits for ever.
Chapter mnemonic
Four conditions for deadlock
One key each. Keep yours. No snatching. Wait in a ring.
If all threads acquire keys in the same global order, which deadlock condition is prevented?
Circular wait. A chain that acquires keys in increasing order cannot close into a ring.
Video lesson · Chapter 1 of 6
Make a prediction
Deadlocks and lock order
1:01Reel
Theory
Read or listen first. About 3 min.
What it is
A deadlock is a group of threads in which each waits for something that only another one of the group can give. Nobody can move, so nobody ever will. With locks, the group is a circle: thread 1 waits for a lock of thread 2, thread 2 for one of thread 3, and the last for one of thread 1.
It is a failure of liveness. Safety says that nothing wrong happens, and a hung program does nothing wrong: it does nothing. That is why it is hard to notice. No exception, no log line, no load.
Related failures are the livelock, in which threads keep reacting to each other without getting on, starvation, in which some get on and one never does, and priority inversion, in which an important thread waits for an unimportant one that does not get to run.
Why it exists
Because finer locks are the usual way to more speed, and the second lock brings the first deadlock. A design with one lock cannot have this problem. Every design with two must say its order.
Because the bug is rare and not local. It depends on timing, and the two pieces of code that make it may be in different files and belong to different teams. Tests with one thread never see it.
Because interviewers ask it in nearly every concurrency round: transfer between two accounts, move between two warehouses, swap two seats. A clear answer takes thirty seconds.
A short history
1960s
In the note EWD 108, Edsger Dijkstra describes the deadly embrace and the banker who lends money without getting stuck. Both appear again in Cooperating Sequential Processes, EWD 123.
1968
J. W. Havender publishes Avoiding Deadlock in Multitasking Systems in the IBM Systems Journal, about how OS/360 was designed: ask for all at once, or ask in a fixed order.
1971
Coffman, Elphick and Shoshani publish System Deadlocks in ACM Computing Surveys, with the four conditions.
1971
Dijkstra's text EWD 310, Hierarchical Ordering of Sequential Processes, contains five philosophers who each need two forks to eat.
1997
The computer of the Mars Pathfinder lander restarts again and again because of priority inversion. Engineers find it and switch on priority inheritance from Earth.
2004
Java 5 adds
Lock.tryLockwith a timeout, and a management interface that can find deadlocked threads.2017
C++17 adds
std::scoped_lock, which takes several mutexes with a deadlock avoidance algorithm.
Words to know
- Lock order
- A rule that says which lock comes before which. Threads take locks only upwards.
- Wait-for graph
- A drawing of who waits for whom. A circle in it is a deadlock.
- Hold and wait
- Keeping one resource while waiting for another.
- Try-lock
- Ask for a lock, and come back with no after a while instead of waiting for ever.
- Back off
- Wait a growing, random time before trying again.
- Victim
- The one that is stopped and rolled back so that the others can go on.
- Livelock
- Everybody is active, and nobody makes progress.
- Starvation
- Somebody waits without end while others are served.
- Open call
- A call to other code made without holding a lock.
- Reentrant lock
- A lock that the thread that holds it may take again.
- Safe state
- A state in which some order exists that lets everybody finish.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Hold one. Each thread has a lock the other needs.
Understand it
Start here
One ladder, one bucket
A race gives a wrong answer. A deadlock gives no answer at all: the program stays alive, uses no processor time, and waits for ever. It is also one of the easiest problems to prevent, once the order of the locks is a rule and not an accident.
Three different illnesses. In a deadlock nobody moves. In a livelock all move and none gets on. In starvation all get on but one.
See it
Six lines that hang
A bicycle rental has several shops. A van moves bikes from one shop to another. Each shop has its own lock, and a move needs both of them, so that nobody counts the bikes in the middle. This code passes every test with one thread:
def move_unsafe(src, dst, n): with src.lock: with dst.lock: src.bikes -= n dst.bikes += nThe unlucky order
Draw it as a graph
Why
Four things must be true at once
In 1971 three authors, Coffman, Elphick and Shoshani, wrote down four conditions. A deadlock needs all four. Break any one and it cannot happen. So every cure on this page is a way of breaking one of them.
The four conditions
1. Mutual exclusion
Only one can have the thing at a time. One ladder cannot be used by two. Broken by: sharing copies, atomics, immutable data.
2. Hold and wait
Somebody holds one thing and waits for another. Broken by: take everything at once, or one lock only.
3. No taking away
Nobody can take a thing from its holder. Broken by: try-lock, timeout, a victim that is rolled back.
4. Circular wait
The waiting forms a circle. Broken by: one global order, so that waiting always points upwards.
Which condition does each cure break?
| Cure | Breaks | Costs | Best when |
|---|---|---|---|
| One lock for all | Hold and wait | Less parallel work | Short sections, first version |
| Global lock order | Circular wait | You need a key to sort by, and discipline | The default answer |
| Take all at once | Hold and wait | You must know the list before you start | Two or three locks, std::scoped_lock |
| Try-lock with timeout | No taking away | Retries, possible livelock, a busy answer | The order is not yours to choose |
| Detection and victim | No taking away | Bookkeeping, work thrown away | Databases, lock managers |
| No shared lock | Mutual exclusion | A different design | One owner, messages, atomics |
Which cure do I reach for?
Design
The circle hides in the class diagram
Locks inside classes make the order invisible. OrderBook locks itself and calls Stock. Stock locks itself and, when bikes come in, calls OrderBook. Each class is correct. Together they can hang.
Bad: two classes call each other with a lock in the hand
1/2One way
A customer places an order. The thread holds the lock of the order book and asks for the lock of the stock.
uses
Good: one direction, and the news leaves after the lock is open
1/3Two leaves
The two classes with locks do not know each other any more. Each locks, works, opens, returns.
uses
Relatives
Livelock, starvation and priority inversion
All of these are liveness failures: something good should happen in the end, and it does not. Interviewers like to hear the difference in one sentence each.
Tell them apart
| Illness | Threads | Processor | What you see | Cure |
|---|---|---|---|---|
| Deadlock | All in the circle blocked | Idle | Requests never return, two stacks in lock | Order, timeout, victim |
| Livelock | All run | Busy | Retries grow, nothing is finished | Random waits, limited tries, one winner by rule |
| Starvation | One waits, others get on | Any | Very long tail for a few | Fair queue, aging, reserved share |
| Priority inversion | High waits for low, medium runs | Busy with medium | An important task misses its time | Priority inheritance, short sections |
| Just slow | Wait, then get on | Any | Long waits that end | Shorter sections, more locks |
Where a thread can be
def rounds(pauses_a, pauses_b, limit=8): """Both take one thing, see that the other is taken, give back, pause.""" for r in range(limit): if pauses_a[r % len(pauses_a)] != pauses_b[r % len(pauses_b)]: return f"round {r + 1}: one of them found both things free" return f"{limit} rounds, nobody has washed a window"print(rounds([10], [10]))print(rounds([7, 13], [12, 4]))import threadingclass TicketLock: def __init__(self): self._gate = threading.Condition() self._next, self._serving = 0, 0 def __enter__(self): with self._gate: mine = self._next self._next += 1 self._gate.wait_for(lambda: self._serving == mine) def __exit__(self, *_): with self._gate: self._serving += 1 self._gate.notify_all()lock, total = TicketLock(), 0def work(): global total for _ in range(200): with lock: total += 1threads = [threading.Thread(target=work) for _ in range(4)]for t in threads: t.start()for t in threads: t.join()print(total)Fairness costs speed: every handover wakes a certain thread, even if another one is awake and could go at once. Java says it in its constructor: new ReentrantLock(true) is fair, and the default is not. Use it when a measured tail hurts, not as a habit.
Hidden
Deadlocks that do not look like two locks
Seven disguises
The same lock twice
A method with the lock calls another method that takes it too. With a plain lock the thread waits for itself. Split into a public method that locks and a private one that does not.
A callback under the lock
You call a listener while you hold the lock. It may take any lock, or wait for a thread that needs yours. Copy the list, open the lock, then call.
Join under the lock
You wait for a thread to end while you hold a lock that this thread needs for its last step.
Wait with a second lock
Waiting on a condition opens its own lock only. An outer lock stays closed, and the one who should wake you needs it.
A pool that waits for itself
All workers wait for jobs that sit in the queue behind them. No lock in sight. See thread pool.
A lock and a database row
One thread has the lock and waits for a row. Another has the row and waits for the lock. Neither side sees the whole circle.
Two full queues
A sends to B and B sends to A, both queues are full, both sides wait to send before they read. Never block on sending in the loop that receives.
Open call
- Change the data under the lock
- Copy what others need to know
- Open the lock
- Then call listeners, network, database
Call from inside
- The lock is held for as long as a stranger wants
- Any lock they take is now ordered after yours
- They may call you back on another thread
- Nobody can review it, because the code is not here
def take(self): # bad: called with self._outer held with self._outer: with self._gate: while not self._items: self._gate.wait() # opens _gate, keeps _outer return self._items.pop()def put(self, item): with self._outer: # never gets in with self._gate: self._items.append(item) self._gate.notify()self._gate, and nothing else. The class above it must not hold a lock here.Choose
Three answers to the same question
A move needs the locks of two shops. How do you keep two opposite moves from hanging?
BreaksLock source, then destination
- How
- Take the locks in the order of the arguments.
- Limit
- Two opposite moves take them in opposite orders. It hangs rarely, so tests pass.
- Choose when
- Never.
WorksOne lock for all shops
- How
- A single lock in the fleet. Every move takes it.
- Limit
- Moves between unrelated shops wait for each other.
- Choose when
- A good first version. Say what you would measure before you split it.
WorksTry both, give back, retry
- How
- Wait a short time for the second lock. If it does not come, release the first, pause at random, and try again.
- Limit
- Needs a limit of tries and a busy answer. Under load it burns time.
- Choose when
- When you cannot sort, for example locks of other people's objects.
StrongSort by shop id
- How
- Lock the smaller id first, whatever the direction of the move.
- Limit
- Needs a unique key that never changes, and everybody must follow it.
- Choose when
- The default. Two lines, no timeouts, and a proof in one sentence.
Find it
It hangs. What now?
From a hang to a line of code
- 1
Take a dump, twice
jstackorjcmd Thread.printfor Java,faulthandlerorpy-spyfor Python,gdbwiththread apply all btfor C++. Ten seconds apart. - 2
Look for the same stacks
Threads that stand at the same
lockline in both dumps are suspects. The Java dump even prints the circle when it finds one. - 3
Write who holds and who waits
Two columns. Draw arrows. The circle is the bug.
- 4
Find the two code paths
Not the thread that is stuck, but the two places that take the locks in different orders.
- 5
Fix the order, not the symptom
Choose one order and change the wrong path. A timeout alone turns a hang into a slow error.
- 6
Keep a guard
A test that runs both paths with a deadline, or a rank check in test builds, so that it does not come back.
import faulthandlerfaulthandler.dump_traceback_later(5, exit=True) # prints all stacks and stopsanswer = sum(range(1000)) # the code under testfaulthandler.cancel_dump_traceback_later()print(answer)Say it
The proof in one sentence
Why can a global order never deadlock? Suppose there were a circle. Look at the thread in it that waits for the lock with the highest number. Somebody in the circle holds that lock and waits for another one. By the rule, that other one must have a higher number still. But we said ours was the highest. So there is no circle.
A minute in the interview
Interviewer
Two moves in opposite directions. What happens?
You
With my first version they can hang: each holds one lock and waits for the other. I fix it by locking the shop with the smaller id first, in both directions.
Interviewer
And if both shops are the same?
You
Then a plain lock would wait for itself. I refuse that call at the top.
Interviewer
Why not a timeout?
You
It would work, but then I need retries, a pause that differs, a limit, and an answer for the caller when I give up. The order costs me two lines and nothing at run time.
Summary
The whole topic in one minute.
A deadlock is a circle of waiting. Four conditions make it possible, and each cure removes one. The default cure is a global order: sort the locks by a key that never changes, take them upwards, and put that rule into one helper.
If you cannot sort, wait with a limit, release what you hold, pause for a random time and give up after a few tries. If work can be undone, as in a database, a detector may find the circle and stop a victim.
The strongest design holds at most one lock and calls nobody while holding it. Check the order itself with ranks, put a deadline on every wait, and save two thread dumps before you restart anything.
- A deadlock is a circle of threads, each waiting for what the next one holds.
- Four conditions together: mutual exclusion, hold and wait, no taking away, circular wait. Break one.
- Default cure: sort by a fixed key and lock upwards.
- Second cure: try-lock, release, random pause, limited tries.
- Never call foreign code, join, or wait for a slow thing with a lock in your hand.
- Livelock moves without progress. Starvation leaves one behind. Priority inversion makes the important one wait for the unimportant.
Sources
- E. W. Dijkstra: Cooperating Sequential Processes (EWD 123)
- E. W. Dijkstra: Hierarchical Ordering of Sequential Processes (EWD 310)
- Coffman, Elphick, Shoshani: System Deadlocks (1971)
- PostgreSQL documentation: deadlocks
- Linux kernel: runtime locking correctness validator
- Java API: ThreadMXBean
- cppreference: std::scoped_lock
- Clang: thread safety analysis
- Glenn Reeves: what happened on Mars (Pathfinder)
- HikariCP: about pool sizing