LOCK B1lock(A);2lock(B);3work();1lock(B);2lock(A);3work();1lock(A);2lock(B);3work();LOCK AAB
Locks A and B; a gold key shows who holds eachCode cards: thread T1 (left) and thread T2 (right)Envelopes: lock requests; a clock: a thread asleep; red loop: the circular waitLock B at the back and lock A at the front; thread T1's code on the left and T2's on the right. A gold key sits on its lock while the lock is free and on the holder's card while it is held. T1 takes A and T2 takes B; each then asks for the other's lock and sleeps, its request parked beside the held lock. The red loop is the circular wait. In the last step both threads take A first, and no loop can form. On the cards, lock(A) is short for pthread_mutex_lock(&A) in C, or A.acquire() in Python. The full C program is in the first step: compiled and run, it usually hangs for ever, because each thread sleeps for one second after its first lock.

Getting stuck

  1. Two threads run at the same time and share two locks, A and B. A lock lets only one thread at a time use something shared. T1 takes A, then B. T2 takes the same locks in the other order: B, then A.

The four conditions

Breaking one

What happens

;; step 1/10 · two-threads
thread T1          thread T2
1  lock(A);        1  lock(B);
2  lock(B);        2  lock(A);
3  work();         3  work();

lock(X)   take lock X; if another thread holds it,
          sleep until it is released
work()    use A and B, then release both

the same program in C99 with POSIX threads:

#define _POSIX_C_SOURCE 200809L
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t B = PTHREAD_MUTEX_INITIALIZER;

void *t1(void *arg) {
    (void)arg;
    pthread_mutex_lock(&A);
    sleep(1);                    /* let the other thread take its first lock */
    pthread_mutex_lock(&B);      /* blocks until B is unlocked */
    puts("T1 done");
    pthread_mutex_unlock(&B);
    pthread_mutex_unlock(&A);
    return NULL;
}

void *t2(void *arg) {
    (void)arg;
    pthread_mutex_lock(&B);
    sleep(1);                    /* let the other thread take its first lock */
    pthread_mutex_lock(&A);      /* blocks until A is unlocked */
    puts("T2 done");
    pthread_mutex_unlock(&A);
    pthread_mutex_unlock(&B);
    return NULL;
}

int main(void) {
    pthread_t x, y;
    pthread_create(&x, NULL, t1, NULL);
    pthread_create(&y, NULL, t2, NULL);
    pthread_join(x, NULL);
    pthread_join(y, NULL);
    puts("both done");
    return 0;
}

The four conditions come from Coffman, Elphick and Shoshani, "System Deadlocks" (ACM Computing Surveys, 1971). They are necessary: if any one is missing, deadlock cannot occur. Deadlock depends on timing. With these two orders, some interleavings finish and some get stuck, so the bug can hide in testing and appear only now and then.