The trap
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.
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.
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.
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.
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.
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.
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.
Same timing as before. Thread 1 runs with A: and takes lock A, which is free.
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.
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.
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.
Why it works
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.
What happens
;; step 1/12 · two-threads
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 ends
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. 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.