Skip to content

Operating Systems 06 deadlock

Mugundan edited this page Nov 27, 2026 · 1 revision

Deadlock

Relevant source files

The following references were used as context for generating this wiki page:

A deadlock is a situation where a group of threads are all waiting for each other, so none of them can ever continue. It is the most common bug that locks introduce. Interviews ask for the four necessary conditions, the ways to handle deadlock, and a worked banker's algorithm.

The banker's algorithm example on this page was computed with a short script and checked by hand.

Purpose and Scope

This page covers the four Coffman conditions, resource-allocation graphs, the four strategies (prevention, avoidance, detection and recovery, ignoring), the banker's algorithm with a worked example, livelock, starvation and priority inversion. Locks themselves are on Synchronization.

The Narrow Bridge Analogy

Two cars meet in the middle of a one-lane bridge. Neither can go forward, and neither will reverse. Each holds part of the bridge and wants the part the other holds.

flowchart LR
    A["Thread A<br/>holds lock 1"] -->|"waits for"| L2["lock 2"]
    B["Thread B<br/>holds lock 2"] -->|"waits for"| L1["lock 1"]
    L1 -.->|"held by"| A
    L2 -.->|"held by"| B
Loading
// illustrative: the classic two-lock deadlock
// Thread A                       // Thread B
pthread_mutex_lock(&m1);          pthread_mutex_lock(&m2);
pthread_mutex_lock(&m2);  // waits pthread_mutex_lock(&m1);  // waits

The Four Necessary Conditions (Coffman)

A deadlock can happen only if all four hold at once. Break any one and deadlock is impossible.

Condition Meaning How to break it
Mutual exclusion A resource can be held by only one thread Use sharable resources (read-only data, lock-free structures); often impossible
Hold and wait A thread holds one resource while waiting for another Request all resources at once, or release everything before asking for more
No preemption Resources can't be taken away forcibly Allow taking them (e.g. trylock and back off, roll back a transaction)
Circular wait A cycle of threads, each waiting for the next Lock ordering: always acquire locks in one global order

Lock ordering is the most practical fix and the answer interviewers usually want.

Sources: Wikipedia: Deadlock (computer science)

Resource-Allocation Graphs

Draw threads as circles and resources as boxes. An arrow from thread to resource means "requests"; from resource to thread means "held by".

flowchart LR
    T1((T1)) -->|"requests"| R2[R2]
    R2 -->|"held by"| T2((T2))
    T2 -->|"requests"| R1[R1]
    R1 -->|"held by"| T1
Loading
Graph Conclusion
No cycle No deadlock
Cycle, one instance of each resource Deadlock
Cycle, several instances of some resource Possible deadlock; must check further

Four Strategies

flowchart TD
    D["Handling deadlock"] --> P["Prevention<br/>design so one condition<br/>can never hold"]
    D --> A["Avoidance<br/>check each request; only grant<br/>if the system stays safe (banker's)"]
    D --> DR["Detection and recovery<br/>let it happen, find cycles,<br/>kill or roll back a thread"]
    D --> I["Ignore it<br/>(ostrich approach)<br/>rare enough; reboot / restart"]
Loading
Strategy Cost Used in
Prevention Restricts how programs use resources Lock ordering in kernels and applications
Avoidance Needs each thread's maximum needs in advance; check on every request Textbooks, some embedded or real-time systems
Detection and recovery Periodic cycle search; victims lose work Databases (abort a transaction)
Ignore None, until it happens Most general-purpose OSes for application locks

Avoidance: The Banker's Algorithm

The idea: grant a request only if, afterwards, there is still some order in which every thread can get its maximum needs and finish. Such an order is a safe sequence, and the state is safe.

flowchart TD
    S["Work = Available<br/>Finish[i] = false for all"] --> F{"Find i with Finish[i] = false<br/>and Need[i] ≤ Work"}
    F -->|"found"| U["Work = Work + Allocation[i]<br/>Finish[i] = true<br/>(i finishes and returns its resources)"]
    U --> F
    F -->|"none"| C{"All Finish = true?"}
    C -->|"yes"| SAFE["Safe state"]
    C -->|"no"| UNSAFE["Unsafe state"]
Loading

Unsafe does not mean deadlocked; it means deadlock might happen, so the request is refused for now.

Worked Example

Five processes, three resource types A, B, C (10, 5 and 7 instances in total).

Process Allocation (A B C) Max (A B C) Need = Max − Allocation
P0 0 1 0 7 5 3 7 4 3
P1 2 0 0 3 2 2 1 2 2
P2 3 0 2 9 0 2 6 0 0
P3 2 1 1 2 2 2 0 1 1
P4 0 0 2 4 3 3 4 3 1

Available = (3 3 2).

Is the state safe? Repeatedly pick a process whose Need fits in Work:

Step Pick Need ≤ Work? Work after it finishes
start 3 3 2
1 P1 1 2 2 ≤ 3 3 2 ✔ 5 3 2
2 P3 0 1 1 ≤ 5 3 2 ✔ 7 4 3
3 P4 4 3 1 ≤ 7 4 3 ✔ 7 4 5
4 P0 7 4 3 ≤ 7 4 5 ✔ 7 5 5
5 P2 6 0 0 ≤ 7 5 5 ✔ 10 5 7

All finish, so the state is safe with sequence P1, P3, P4, P0, P2. Other safe sequences also exist; any one is enough.

P1 requests (1 0 2). Request ≤ Need (1 2 2) ✔ and ≤ Available (3 3 2) ✔. Pretend to grant it: Available becomes (2 3 0), P1's Allocation (3 0 2), Need (0 2 0). Re-running the check finds the same safe sequence P1, P3, P4, P0, P2, so the request is granted.

Then P0 requests (0 2 0). It fits in Available (2 3 0). Pretend to grant it: Available becomes (2 1 0) and P0's Need (7 2 3). Now no process's Need fits in (2 1 0): P1 needs (0 2 0), P3 needs (0 1 1), and the others need more. The state is unsafe, so P0 must wait, even though the resources are free.

Sources: Wikipedia: Banker's algorithm

Detection and Recovery

With single-instance resources, keep a wait-for graph (thread → thread it is waiting on) and look for a cycle. With multiple instances, run a banker's-style check using current requests instead of maximum needs.

Recovery options: kill one or more threads in the cycle, or preempt a resource and roll its owner back to a checkpoint. Choose a victim that has done the least work or holds the most resources.

Livelock, Starvation and Priority Inversion

Problem What happens Example Fix
Deadlock Everyone waits; nothing runs Two locks, opposite order Lock ordering
Livelock Everyone keeps running but makes no progress Two people in a corridor both stepping aside the same way, again and again; threads that trylock, fail, release, retry in sync Random back-off
Starvation Some thread never gets the resource, while others progress Low priority never scheduled; writers starved by readers Aging, fair queues
Priority inversion A high-priority thread waits for a lock held by a low-priority one, while a medium-priority thread keeps the low one off the CPU Mars Pathfinder, 1997 Priority inheritance: the lock holder temporarily gets the waiter's priority
sequenceDiagram
    participant L as Low priority
    participant M as Medium priority
    participant H as High priority
    L->>L: acquires lock
    H->>H: wakes, needs lock: blocks
    M->>M: wakes, runs (beats L)
    Note over L,H: H waits for L, L waits for M: H effectively has lowest priority
    Note over L: with priority inheritance, L runs at H's priority,<br/>releases the lock, H continues
Loading

Sources: Wikipedia: Priority inversion

Common Traps

  • All four conditions are needed; a cycle alone is not enough with multi-instance resources.
  • Unsafe ≠ deadlocked.
  • In the banker's algorithm, first check Request ≤ Need (otherwise it is an error) and Request ≤ Available (otherwise wait).
  • Deadlock is permanent waiting; starvation is indefinite but not necessarily permanent.

Interview Questions

  1. What are the necessary conditions for deadlock? Mutual exclusion, hold and wait, no preemption, circular wait, all at the same time.
  2. How do you prevent deadlock in practice? Acquire locks in a fixed global order; or use trylock with back-off; or hold at most one lock at a time.
  3. Deadlock vs starvation vs livelock? Deadlock: everyone blocked forever. Starvation: one thread is never served while others run. Livelock: threads keep acting but make no progress.
  4. What does the banker's algorithm do? Before granting a request it simulates whether all processes could still finish in some order using their declared maximums; if not, the request waits.
  5. Why is the banker's algorithm rarely used in general-purpose OSes? Processes rarely know their maximum needs, the number of processes changes, and the check on every request is costly.
  6. What is priority inversion and how is it fixed? A high-priority task waits on a lock held by a low-priority task that is preempted by medium-priority work. Fix with priority inheritance or priority ceiling.

Key Points

  • Deadlock needs mutual exclusion, hold and wait, no preemption and circular wait; break one to prevent it.
  • The banker's algorithm grants requests only when a safe sequence still exists.
  • Know the differences between deadlock, livelock, starvation and priority inversion.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally