Card 03/ 08

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.

The four conditions, and what removing each one would mean
ConditionMeansRemoving it would mean
Mutual exclusionA lock is held by one thread at a timeNot using locks at all
Hold and waitA thread holding one lock asks for anotherTaking every lock at once, or none
No preemptionA lock cannot be taken away from its holderA timeout that makes a thread let go
Circular waitA closes the cycle: A waits for B, B waits for AA 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.