AlgoViz

Deadlocks and lock order

hard 65 min

Two 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

0:00 / 5:12

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

  1. 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.

  2. 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.

  3. 1971

    Coffman, Elphick and Shoshani publish System Deadlocks in ACM Computing Surveys, with the four conditions.

  4. 1971

    Dijkstra's text EWD 310, Hierarchical Ordering of Sequential Processes, contains five philosophers who each need two forks to eat.

  5. 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.

  6. 2004

    Java 5 adds Lock.tryLock with a timeout, and a management interface that can find deadlocked threads.

  7. 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.

Step 1 of 4

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.

Window cleaning

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:

Python
def move_unsafe(src, dst, n):    with src.lock:        with dst.lock:            src.bikes -= n            dst.bikes += n
Correct with one thread. With two threads, now and then, it never comes back.

The unlucky order

Look at the code again: both threads run the same function. The order comes from the arguments, so you cannot see it in the text.

Draw it as a graph

The wait-for graph. With locks that have one owner, a circle in this graph is a deadlock, and every deadlock on locks is a circle in it.

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?

CureBreaksCostsBest when
One lock for allHold and waitLess parallel workShort sections, first version
Global lock orderCircular waitYou need a key to sort by, and disciplineThe default answer
Take all at onceHold and waitYou must know the list before you startTwo or three locks, std::scoped_lock
Try-lock with timeoutNo taking awayRetries, possible livelock, a busy answerThe order is not yours to choose
Detection and victimNo taking awayBookkeeping, work thrown awayDatabases, lock managers
No shared lockMutual exclusionA different designOne owner, messages, atomics
The third condition is the reason a mutex cannot be repaired from outside: you may not open another thread's lock, because the data behind it is half changed.

Which cure do I reach for?

Most questions end in the first two boxes. Say so, instead of showing the cleverest one.

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

OrderBook- lock: Lock- open: List<Order>+ place(o): locks, calls Stock+ arrived(): locks

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

A circle of calls between classes that hold locks is a warning you can see in a design review. The page on circular dependencies shows how to break such circles.

Good: one direction, and the news leaves after the lock is open

OrderBook- lock: rank 10- open: List<Order>+ add(o)+ waiting(): List<Order>Stock- lock: rank 20- bikes: int+ take(n): bool+ put(n)

1/3Two leaves

The two classes with locks do not know each other any more. Each locks, works, opens, returns.

uses

The price: between the two calls another thread may act. Reserve first and confirm later, as on the page about correctness.

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

IllnessThreadsProcessorWhat you seeCure
DeadlockAll in the circle blockedIdleRequests never return, two stacks in lockOrder, timeout, victim
LivelockAll runBusyRetries grow, nothing is finishedRandom waits, limited tries, one winner by rule
StarvationOne waits, others get onAnyVery long tail for a fewFair queue, aging, reserved share
Priority inversionHigh waits for low, medium runsBusy with mediumAn important task misses its timePriority inheritance, short sections
Just slowWait, then get onAnyLong waits that endShorter sections, more locks
Always rule out the last row first. A thread dump taken twice, ten seconds apart, shows whether anything moved.

Where a thread can be

Waiting is normal. The trouble is an arrow that leads nowhere.
Python
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]))
Livelock in slow motion. Equal pauses meet again in every round. Different pauses end it in the first round.
Edit and run it in your browser
Python
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)
Starvation and its cure. A fair lock hands out numbers, as at a bakery counter.
Edit and run it in your browser

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
Python
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()
The wait on the condition opens 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. 1

    Take a dump, twice

    jstack or jcmd Thread.print for Java, faulthandler or py-spy for Python, gdb with thread apply all bt for C++. Ten seconds apart.

  2. 2

    Look for the same stacks

    Threads that stand at the same lock line in both dumps are suspects. The Java dump even prints the circle when it finds one.

  3. 3

    Write who holds and who waits

    Two columns. Draw arrows. The circle is the bug.

  4. 4

    Find the two code paths

    Not the thread that is stuck, but the two places that take the locks in different orders.

  5. 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. 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.

Python
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)
A watchdog for tests: if the block is not done in time, Python prints the stacks of all threads.
Edit and run it in your browser

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

  1. Interviewer

    Two moves in opposite directions. What happens?

  2. 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.

  3. Interviewer

    And if both shops are the same?

  4. You

    Then a plain lock would wait for itself. I refuse that call at the top.

  5. Interviewer

    Why not a timeout?

  6. 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