How a deadlock happens

· 2 min read

#how-it-works#os

A deadlock is when threads wait on each other forever and the program stops. The idea to keep: each thread holds something the other one needs.

The short version

Say Thread 1 holds Lock A and Thread 2 holds Lock B. Thread 1 now asks for Lock B, and Thread 2 asks for Lock A. Each waits for a lock its owner will not release, because the owner is waiting too. Nothing crashes, the program just stops moving. Whether it happens depends on thread timing, so it can show up only some of the time.

Two threads wait for each other's lock Thread 1 holds Lock A and Thread 2 holds Lock B. Thread 1 waits for Lock B and Thread 2 waits for Lock A, so the dashed arrows cross and neither thread can move. Thread 1 Thread 2 Lock A Lock B 1 holds 2 holds 3 waits 4 waits
Simplified: each thread holds one lock and waits for the other; neither can move.

Step by step

  1. Thread 1 locks A.
  2. Thread 2 locks B.
  3. Thread 1 asks for B and waits.
  4. Thread 2 asks for A and waits.
  5. Neither lock is released, so neither thread runs again.

One thread can also deadlock itself, for example by relocking a normal POSIX mutex it already holds. In Swift, Apple's docs say a sync call that targets the queue it is already running on deadlocks:

let queue = DispatchQueue(label: "demo")
queue.sync {
    queue.sync { }
}

Why it matters

The usual defense is to take locks in the same order everywhere, so the circle cannot form; the Linux kernel's lockdep tool checks for this. My reading: the rule is simple, but keeping it across a large codebase takes discipline, and in Swift async is the safer choice when you are unsure which queue you are on.

Sources