Card 03/ 08
All 8 cards
ConceptDifficulty: Intermediate1 min
The Four Conditions a Deadlock Needs, All at the Same Time
Deadlock has a reputation for being mysterious and is the opposite. It needs four things to be true at once, and removing any one of them makes it impossible.
| Condition | Means | Removing it would mean |
|---|---|---|
| Mutual exclusion | A lock is held by one thread at a time | Not using locks at all |
| Hold and wait | A thread holding one lock asks for another | Taking every lock at once, or none |
| No preemption | A lock cannot be taken away from its holder | A timeout that makes a thread let go |
| Circular wait | A closes the cycle: A waits for B, B waits for A | A fixed order every thread takes locks in |
The first is the point of a lock and is not going anywhere. The second is hard to avoid when an operation genuinely spans two objects. The third is what a timeout removes, and it turns a hang into a failure rather than into success.
The fourth is the one to attack, and it is the only one you can remove without giving up something you wanted. If every thread in the program takes locks in the same order, a cycle cannot form.
So the practical rule that comes out of a four-part theory is one sentence: decide a global order for your locks, and take them in it, everywhere.