How a deadlock happens
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.
Step by step
- Thread 1 locks A.
- Thread 2 locks B.
- Thread 1 asks for B and waits.
- Thread 2 asks for A and waits.
- 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
- The Java Tutorials: Deadlock — two threads blocked forever, each waiting for the other; the outcome depends on thread timing
- pthread_mutex_lock (POSIX) — relocking a normal mutex from its owner deadlocks
- DispatchQueue.sync(execute:) — a call that targets the current queue results in deadlock
- Runtime locking correctness validator — taking locks in opposite orders (AB-BA) is a lock inversion deadlock; the validator finds it before it hangs