Operating System Slides 📂 Introduction · 12 of 22 36 min read

Deadlock in OS — System Model, Coffman Conditions & Handling Methods

Master deadlock in operating systems: the system model, the four Coffman conditions, reading a resource-allocation graph and its cycles, and the four handling methods — prevention, avoidance (safe state), detection and recovery, plus the ostrich approach — with animated diagrams throughout.

🔒

Deadlock in OS — System Model, Coffman Conditions & Handling

When every process waits for a resource another is holding, nobody moves — forever. Learn the four conditions that cause deadlock, how to read a resource-allocation graph, and the four ways to handle it. With animated diagrams.
4 Coffman Conditions Resource Graph Prevent · Avoid Detect · Recover

Press Next → or use ← → arrow keys

Section 01

The Story That Explains Deadlock

Two cars reach opposite ends of a single-lane bridge at the same moment. Each driver wants to cross, but the bridge fits only one car. Neither will reverse — each insists the other should back up — and neither can go forward, because the other is in the way. Both engines run, both drivers wait. No motion is possible, forever.

Swap "cars" for processes and "bridge" for a shared resource — a printer, a disk, a database row, a lock — and you have a deadlock.
🛑
The Formal Definition

A set of processes is deadlocked when every process in the set is waiting for an event — usually a resource release — that can be caused only by another process in the same set. Since none can proceed, none will ever cause that event. The wait is permanent.

Section 02

System Model — Resources & Their Life Cycle

① REQUESTblock if unavailable ② USEdo the actual work ③ RELEASEgive it back to the OS
📦
Resource Types & Instances

The OS manages resource types (R₁, R₂, …) — CPU, memory, printers, files — each with one or more identical instances (e.g. 8 CPU cores, 3 printers). Every process follows the same cycle: request (and block if it's taken), use, then release. Trouble starts when a process holds one resource while blocking for another.

Section 03

The Four Coffman Conditions

🔒
Mutual Exclusion
non-sharable
At least one resource can be held by only one process at a time — it can't be shared while in use.
Hold and Wait
grab, then block
A process holds at least one resource while waiting to acquire others held by other processes.
🚫
No Preemption
no taking back
A resource can be released only voluntarily by the process holding it — never forcibly taken away.
🔄
Circular Wait
the closing loop
A chain P₀ → P₁ → … → Pₙ → P₀ where each process waits for a resource the next one holds.
🎯
All Four Must Hold at Once

Deadlock is possible only when all four conditions hold simultaneously. This is the key insight: break any single one — by design or at runtime — and deadlock becomes impossible. Every prevention strategy is just an attack on one of these four.

Section 04 · Diagram

Watch a Deadlock Form

P1 P2 R1Printer • R2Scanner • holds holds wants R2 wants R1 🛑 DEADLOCK · circular wait
🔄
P1 → R2 → P2 → R1 → P1

P1 holds the printer (R1) and wants the scanner (R2). P2 holds the scanner and wants the printer. Each is waiting for exactly what the other is holding — the loop closes and neither can move. Every Coffman condition is present at once.

Section 05

The Resource-Allocation Graph (RAG)

🗺️ How to read a RAG
Node
A circle is a process Pᵢ; a rectangle is a resource Rⱼ, with a dot per instance.
Request
An edge Pᵢ → Rⱼ means the process is requesting that resource.
Assignment
An edge Rⱼ → Pᵢ means the resource is assigned to (held by) the process.
What the graph showsConclusion
No cycleNo deadlock — guaranteed
Cycle + all resources single-instanceDeadlock exists — guaranteed
Cycle + some multi-instance resourcesDeadlock may exist — run a detection algorithm
Section 06 · Diagram

A Cycle of Three — RAG Construction

P1 R2 P2 R3 P3 R1 🛑 CYCLE DETECTED P1→R2→P2→R3→P3→R1→P1
🔗
Follow the Loop

Red dashed = a request, green solid = an assignment. Trace them clockwise and they close a cycle. Because every resource here has a single instance, this cycle guarantees deadlock.

Section 07

Four Ways to Handle Deadlock

🛡️
Prevention
Structurally break one of the four Coffman conditions at design time, so deadlock can never form.
🧭
Avoidance
Use knowledge of future needs to grant only requests that keep the system in a safe state (Banker's Algorithm).
🔍
Detection + Recovery
Let deadlock happen, run a detection algorithm periodically, then recover by killing or preempting.
🙈
Ignore (Ostrich)
Pretend it never happens. Rare enough on desktops that the user just reboots — what Windows, macOS & Linux do.
⚖️
A Cost Spectrum

Prevention and avoidance pay up front in reduced concurrency and per-request checks; detection pays periodically; ignoring pays nothing until the rare crash. The right choice depends on how catastrophic a deadlock would be.

Section 08

Prevention — Break One Condition

Break…HowCost / Problem
Mutual ExclusionMake resources sharable (read-only files, spooled printers)Impossible for intrinsically non-sharable things like locks
Hold and WaitRequest everything at once, or release all before asking for moreLow utilisation; possible starvation
No PreemptionForcibly reclaim held resources when a further request can't be metOnly works for state-saveable resources (CPU, memory) — not printers
Circular WaitNumber the resource types; require acquisition in increasing orderMost practical — widely used in real kernels
🔢
Ordering Is the Winner

Imposing a total order on resources and always locking in increasing order makes a cycle impossible — you can never wait "backwards." It's simple, cheap, and the technique production kernels and databases actually use.

Section 09

Avoidance — The Safe State

State Space UNSAFE DEADLOCK SAFE grant unsafe request
🧭
Stay Inside the Safe Zone

A state is safe if there's some order — a safe sequence — in which every process can finish with the resources available. Avoidance grants a request only if the result stays safe. Note: unsafe ≠ deadlock — an unsafe state may lead to deadlock but doesn't guarantee it. The Banker's Algorithm is the classic safe-state check (its own tutorial).

Section 10

Detection — Find the Cycle After the Fact

If you allow deadlocks, you must periodically check for them. The detection algorithm walks the Available, Allocation and Request matrices, simulating which processes could finish.

# Deadlock detection — m resource types
Work   = Available
Finish[i] = (Allocation[i] == 0)   # idle procs are trivially "finished"

while ∃ i : Finish[i] == false and Request[i] <= Work:
    Work      = Work + Allocation[i]   # pretend it finishes and releases
    Finish[i] = true

if ∃ i : Finish[i] == false:
    return "DEADLOCK"   # those processes are stuck
else:
    return "NO DEADLOCK"
⏱️
How Often to Run It?

Run it too rarely and deadlocks linger, wasting resources; too often and the algorithm's own cost bites. A common trigger is "whenever a request can't be granted." Any process still marked Finish[i] == false at the end is deadlocked.

Section 11

Recovery — Break the Cycle

P1cost = 100 P2 cost = 40 ★ victim P3cost = 80 P1→R2 P2→R3 P3→R1
🎯
Kill the Cheapest Victim

To recover, either terminate processes or preempt their resources. Pick the victim that costs least to lose — here P2 (cost 40). Killing it frees its resources, breaks the cycle, and the survivors proceed. Cap how often any one process can be the victim, or you risk starvation.

Section 12

Which Method to Choose?

MethodWhen to useOverheadReal-world example
🛡️ PreventionSafety-critical systemsDesign-time disciplineAvionics, medical devices
🧭 AvoidanceMax needs known in advanceHigh — check per requestReal-time systems, known workloads
🔍 DetectionLong-running serversPeriodic algorithm costOracle, PostgreSQL, MySQL
🙈 IgnoreConsumer OS, deadlocks rareZeroWindows, macOS, Linux desktop
🗄️
Databases Detect; Desktops Ignore

Databases run millions of concurrent transactions, so they detect deadlocks and abort the cheapest transaction. Your laptop, where a deadlock is a once-in-a-blue-moon event, just lets you reboot — paying zero overhead every other day.

Section 14

Seven Rules for Deadlock

🔒 DEADLOCK · CHECKLIST
1
Deadlock needs all four Coffman conditions at once — mutual exclusion, hold-and-wait, no preemption, circular wait.
2
Break any one condition and deadlock is impossible — every prevention trick does exactly this.
3
In a resource graph: no cycle → no deadlock; a cycle with single-instance resources → deadlock.
4
Resource ordering is the most practical prevention — always acquire in increasing order.
5
Avoidance keeps the system in a safe state; remember unsafe ≠ deadlock.
6
Recovery means terminate or preempt the cheapest victim — and cap victimisation to avoid starvation.
7
Match the method to the stakes: prevent in avionics, detect in databases, ignore on desktops.
FINAL

Deadlock — Understood End to End

4Coffman conditions
1Break one to be safe
RAGCycle = trouble
4Handling methods
🙈Desktops just reboot
🎯
You Can Now Reason About Any Deadlock

From the four conditions and the resource-allocation graph, through prevention, avoidance, detection and recovery — you can spot a potential deadlock, prove whether a graph is deadlocked, and choose the right handling strategy for the stakes involved.

📚
Where To Go Next

The natural sequel is the Banker's Algorithm — the full safe-state check with Allocation, Max, Need and Available matrices worked out step by step, which turns "avoidance" from a concept into a procedure you can run.

🔒 End of tutorial · Press to review, or click Restart