Deadlock Prevention
Break a Coffman condition so a cycle cannot form: no hold-and-wait, preemption, ordering.
Level: intermediate
What is it?
Deadlock prevention designs resource rules so at least one of the four necessary Coffman conditions cannot hold: mutual exclusion, hold and wait, no preemption, and circular wait. A system may require resources upfront, allow certain resources to be reclaimed, or impose a global ordering on locks.
Why does it matter?
Prevention gives a structural guarantee against a class of deadlocks, but can reduce concurrency or complicate resource use. The engineering goal is to remove the unsafe pattern without making ordinary workflows unnecessarily restrictive.
Mental model
To stop a traffic gridlock, change the road rules so the circular wait can never be completed. The solution avoids one necessary condition rather than trying to guess whether a particular state will become deadlocked.
How it works
- Mutual exclusion cannot be removed for inherently exclusive resources.
- Hold-and-wait can be reduced by requesting all required resources at once, although this may waste capacity.
- Preemption is possible for some resources but not for arbitrary stateful operations.
- A global lock ordering prevents circular wait when every participant follows the same order.
- Prevention is different from avoidance: avoidance inspects the current allocation and grants requests only if the resulting state remains safe.
Steps
- Thread A needs locks L1 and L2; thread B needs the same pair.
- Without a rule, A can hold L1 while waiting for L2, while B holds L2 waiting for L1.
- Declare and enforce one ordering, L1 before L2, in all code paths.
- Because both threads acquire in the same order, this two-lock circular wait cannot form.
Real-world usage
- Reviewing lock acquisition order in services and libraries.
- Comparing deadlock prevention, avoidance, detection, and recovery for exams.
- Writing concurrency guidelines for a codebase.
Common mistakes
- Calling every timeout a deadlock-prevention strategy; timeout-and-retry is a different recovery approach.
- Introducing lock ordering in one code path but violating it in another.
- Removing a necessary condition without checking the cost to throughput or usability.
Interview questions
Which Coffman condition does a global lock order break?
Circular wait. All threads acquire locks in a consistent order, so a cycle of wait dependencies cannot form.
How does prevention differ from avoidance?
Prevention structurally breaks a necessary deadlock condition; avoidance makes per-request decisions based on whether the resulting state remains safe.