LOCK A#1LOCK B#2THREAD 1THREAD 21with A:2 with B:3 work()1with B:2 with A:3 work()1with A:2 with B:3 work()AB
Back: locks A and B, each key at home on its lockMiddle: the two threads; front: each thread's codeKeys move to the thread that holds them; a clock and a red arrow mean waits forTwo locks at the back, each with its key; two threads in the middle; each thread's Python code in front. With opposite orders, each thread holds one key and waits for the other's: the red arrows close a circle, a deadlock. With one order, A (1) before B (2), Thread 2 waits holding nothing, Thread 1 finishes, and then Thread 2 finishes. 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 trap

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

One order

Why it works

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.