Preventing deadlock with lock ordering
About this lesson
Two threads each need the same two locks. If they take them in opposite orders, one badly timed switch leaves each thread holding the lock the other wants, and both wait forever. Watch that circle form, then fix it with one rule: number every lock and always take locks in rising order. The lesson The four conditions for deadlock names the conditions this rule breaks, Resource allocation graphs draws the circle, and Locks, spinlocks and atomic instructions explains the locks themselves.
Two threads, two locks
Two threads share two locks, A and B. A lock is like a key only one thread can hold; any other thread that asks for it must wait. Each thread needs both keys to do its work, but they ask in opposite orders.
A = threading.Lock() B = threading.Lock()
thread 1 thread 2
with A: with B:
with B: with A:
work() work()
with X: take lock X (wait while another thread holds it),
release it when the block endsRead the lesson step by step
Two threads, two locks
Two threads share two locks, A and B. A lock is like a key only one thread can hold; any other thread that asks for it must wait. Each thread needs both keys to do its work, but they ask in opposite orders.
A = threading.Lock() B = threading.Lock() thread 1 thread 2 with A: with B: with B: with A: work() work() with X: take lock X (wait while another thread holds it), release it when the block endsThread 1 takes A
Thread 1 runs its first line, with A:. Lock A is free, so Thread 1 takes it and carries on. In Python, with takes the lock when the block starts and releases it when the block ends.
thread 1 with A: A is free -> taken lock holder A thread 1 B -Thread 2 takes B
The scheduler switches threads. Thread 2 runs its first line, with B:. Lock B is free too, so Thread 2 takes it. Each thread now holds one key.
switch to thread 2 thread 2 with B: B is free -> taken lock holder A thread 1 B thread 2Thread 1 must wait
Thread 1's second line asks for B. Thread 2 holds B, so Thread 1 blocks: it sleeps until B is released. It keeps holding A while it waits.
switch to thread 1 thread 1 with B: B is held by thread 2 -> blocked thread 1 holds A, waits for B (held by thread 2)Thread 2 must wait
Thread 2's second line asks for A. Thread 1 holds A, so Thread 2 blocks too, still holding B. Each thread now waits for a key the other one holds.
switch to thread 2 thread 2 with A: A is held by thread 1 -> blocked thread 1 holds A, waits for B (held by thread 2) thread 2 holds B, waits for A (held by thread 1)A circle: deadlock
Thread 1 waits for Thread 2, and Thread 2 waits for Thread 1: a circle. Neither can ever go on. All four conditions hold: mutual exclusion, hold and wait, no preemption and circular wait. Break any one and deadlock cannot happen.
wait-for circle: thread 1 -> thread 2 -> thread 1 mutual exclusion one holder per lock yes hold and wait each holds one, waits for one yes no preemption nobody can take a lock away yes circular wait the circle above yes every reachable state of this pair of programs: 13 of those, deadlocked: 1 (the one shown)The rule: one order
Start again with one rule. Number every lock, A is 1 and B is 2, and always take locks in rising order. Thread 2's code is rewritten to take A first, then B. Thread 1 already follows the rule.
rank A = 1 B = 2 rule hold lock n -> only ask for locks above n thread 1 (unchanged) thread 2 (rewritten) with A: with A: with B: with B: work() work() the same rule in C (C99, POSIX threads): #define _POSIX_C_SOURCE 200809L #include <pthread.h> #include <stdio.h> static pthread_mutex_t lock[2] = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER }; static int balance[2] = { 100, 100 }; /* move money; always lock the lower-numbered account first */ static void transfer(int from, int to) { int lo = from < to ? from : to, hi = from < to ? to : from; pthread_mutex_lock(&lock[lo]); pthread_mutex_lock(&lock[hi]); balance[from] -= 1; balance[to] += 1; pthread_mutex_unlock(&lock[hi]); pthread_mutex_unlock(&lock[lo]); } static void *t1(void *arg) { (void)arg; for (int i = 0; i < 100000; i++) transfer(0, 1); return NULL; } static void *t2(void *arg) { (void)arg; for (int i = 0; i < 100000; i++) transfer(1, 0); return NULL; } int main(void) { pthread_t a, b; pthread_create(&a, NULL, t1, NULL); pthread_create(&b, NULL, t2, NULL); pthread_join(a, NULL); pthread_join(b, NULL); printf("%d %d\n", balance[0], balance[1]); return 0; } prints 100 100Thread 1 takes A again
Same timing as before. Thread 1 runs with A: and takes lock A, which is free.
thread 1 with A: A is free -> taken lock holder A thread 1 B -Thread 2 waits, holding nothing
The scheduler switches. Thread 2 now asks for A first, and Thread 1 holds it, so Thread 2 blocks. But it blocks holding nothing, so lock B stays free for Thread 1.
switch to thread 2 thread 2 with A: A is held by thread 1 -> blocked thread 2 holds nothing, waits for A lock B freeThread 1 finishes
Thread 1 takes B, which is free, does its work, then leaves both with blocks, releasing B and then A. Thread 2 was waiting for A, so it can run again.
switch to thread 1 thread 1 with B: B is free -> taken thread 1 work() thread 1 end of blocks: release B, release A thread 2 A is free: no longer blockedThread 2 finishes
Thread 2 takes A, then B, does its work and releases both. Both threads are done. Thread 2 waited a little while, but nobody waited forever.
thread 2 with A: taken thread 2 with B: taken thread 2 work() thread 2 release B, release A both threads finishedWhy no circle can form
A thread holding lock n only ever waits for a lock numbered above n. A circle of waits would have to come back down to n, which the rule forbids. That breaks circular wait. Linux keeps a lock order, and its lockdep tool checks it.
every schedule, checked exhaustively by the model: opposite orders (A,B / B,A) 13 states, 1 deadlock one order (A,B / A,B) 12 states, 0 deadlocks the same check as a Python simulation: def run(order1, order2, turns): code = {1: order1, 2: order2} held = {} # lock -> thread holding it got = {1: 0, 2: 0} # locks each thread has taken for t in turns: # the scheduler picks who runs if got[t] == 2: continue # finished want = code[t][got[t]] if want in held: continue # held by the other: wait held[want] = t got[t] += 1 if got[t] == 2: # has both: work, then release for lock in code[t]: del held[lock] stuck = [t for t in (1, 2) if got[t] < 2] return "deadlock" if stuck else "both finished" turns = [1, 2, 1, 2, 1, 2] print(run("AB", "BA", turns)) # opposite orders print(run("AB", "AB", turns)) # one order prints: deadlock both finished
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01Thread 1 runs with A: then with B:, and Thread 2 runs with B: then with A:. When can they deadlock?
If one thread takes both locks before the other starts, it finishes and releases them. The deadlock needs the bad timing: each holds its first lock and then asks for the one the other holds.
02Which of the four deadlock conditions does a global lock order break?
Threads still hold locks exclusively and still wait while holding, and nobody takes locks away. But a thread holding lock n only waits for higher-numbered locks, so the waits can never form a circle.
03With the rule A (1) before B (2), Thread 1 holds A and Thread 2 asks for A. What happens?
Thread 2 must take A before B, so it blocks before it holds anything. B stays free, Thread 1 finishes and releases both locks, and then Thread 2 runs.
04A function transfer(x, y) locks two accounts passed as arguments. Callers pass them in any order. How can it keep a lock order?
transfer(0, 1) and transfer(1, 0) must take the locks in the same order. Ordering by a fixed key (the C example uses the array index; OSTEP shows lock addresses) does that whatever order the caller uses.
05Using trylock and letting go when a lock is busy also prevents deadlock. What new problem can it cause?
This breaks the no-preemption condition, because a thread gives up a lock it already holds. Two threads can keep backing off and retrying in step, so neither gets anywhere. That is livelock.
Glossary
- Lock
- A variable that only one thread can hold at a time. A thread that asks for a held lock blocks until the holder releases it. Also called a mutex.
- Deadlock
- A state where a group of threads each wait for something another one in the group holds, so none of them can ever continue.
- Circular wait
- A circle of threads in which each one waits for a lock held by the next. It is one of the four conditions every deadlock needs.
- Hold and wait
- A thread keeps the locks it already holds while it waits for another one.
- Lock ordering
- A rule that gives every lock a rank and makes every thread take locks in rising rank. It makes circular wait impossible.
- Blocked
- The state of a thread that cannot run until something happens, such as a lock being released. It uses no CPU time while it waits.
- Livelock
- Threads keep running and reacting to each other, for example backing off and retrying, but none of them makes progress.
- lockdep
- A tool built into the Linux kernel that records the order in which locks are taken and warns when two locks are taken in opposite orders.
Notes and sources
- The four conditions are from Coffman, Elphick and Shoshani (1971). Prevention makes one of them impossible by the way the code is written. The banker's algorithm lesson covers avoidance, and Detecting and recovering from deadlock covers the third approach.
- The other three conditions can be broken too, at a cost. Take every lock you need at once, behind one global lock (no hold and wait). Use trylock and let go when a lock is busy (no "no preemption"), which can livelock: threads keep backing off and retrying. Or avoid locks with atomic instructions.
- When a function receives two locks as arguments, it can order them by address: compare the two pointers and lock the higher (or lower) one first, as OSTEP shows. The C example orders two locks by their index in one array, which is the same idea.
- Large systems use a partial order: only locks that can be held at the same time need an order between them. Linux's file memory-map code (mm/filemap.c) lists its lock orders in a comment at its top.
- The bad version deadlocks only if the switch comes after one thread took its first lock and before it took its second. Most runs finish, which is why lock-order bugs slip through testing and why tools such as lockdep check the order itself.
- The keys are a picture. A lock is a small variable in memory; holding the key means having acquired the lock. A blocked thread usually sleeps, using no CPU time, until the lock is released.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 32: Common Concurrency Problems
- Berkeley CS162, Lecture 13: Scheduling 4: Realtime Scheduling (Con't), Deadlock
- MIT 6.1810 (2024), lecture notes: Locking
- Linux kernel documentation: Runtime locking correctness validator (lockdep)
- POSIX via Linux man-pages: pthread_mutex_lock(3p)
- Python documentation: threading, Lock objects
Quiz Unlocks after the last step.