OS · Deadlocks

Deadlocks

The four conditions, prevention vs avoidance vs detection, and the banker’s algorithm.

Operating Systems Basics → Interview
01

What is a Deadlock?

A deadlock is a cycle where each process holds a resource and waits for one another process holds — so none can proceed, forever. Two threads, two locks, grabbed in opposite order, is the textbook case.

Classic AB / BA deadlock
Thread 1: lock(A) … lock(B)
Thread 2: lock(B) … lock(A)

If both grab their first lock, each now
waits on the lock the other holds → stuck.
02

The Four Coffman Conditions

A deadlock is possible only if all four hold at once. Break any one and deadlock cannot occur:

ConditionMeaningBreak it by…
Mutual exclusionResource held exclusivelyMaking resources shareable (not always possible)
Hold and waitHold one, wait for anotherGrab all resources at once, or none
No preemptionCan’t force a releaseAllowing the OS to preempt/rollback
Circular waitA cycle of waitingOrdering resources and always locking in that order
03

Handle It: Prevent / Avoid / Detect

StrategyIdeaCost
PreventionDesign so a Coffman condition can’t holdCan waste resources
AvoidanceGrant only if system stays "safe" (Banker’s)Needs max-need known upfront
Detection + recoveryLet it happen, find cycles, kill/rollbackRecovery is disruptive
OstrichIgnore it (reboot if rare)What most OSes actually do
The Banker’s algorithm is deadlock avoidance: before granting a request it simulates the allocation and only proceeds if a safe sequence still exists in which every process can finish.
04

Practical Fix: Lock Ordering

In real code, the cheapest prevention is a global lock ordering: every thread acquires locks in the same fixed order, which removes the circular-wait condition entirely.

Deadlock-free
  • Always lock A before B, everywhere
Deadlock-prone
  • Thread 1 locks A→B, Thread 2 locks B→A
05

Interview Questions

Name the four conditions for deadlock.

Mutual exclusion, hold-and-wait, no preemption, and circular wait — all four must hold simultaneously.

Deadlock prevention vs avoidance?

Prevention structurally negates one of the four conditions upfront. Avoidance allows them but checks each allocation dynamically (Banker’s algorithm) to keep the system in a safe state.

Simplest way to prevent deadlock in application code?

Impose a global lock-acquisition order so no cycle can form (breaks circular wait). Also use lock timeouts / try-lock as a backstop.

What does the Banker’s algorithm need to know?

Each process’s maximum possible demand for each resource type, plus current allocations and availability, so it can test for a safe sequence.

Quick Quiz

1. How many Coffman conditions must hold for deadlock?
2. Enforcing a global lock order breaks which condition?
3. The Banker’s algorithm is an example of…
4. Most general-purpose OSes handle deadlock by…
5. Two threads locking A→B and B→A can cause…