Repository navigation
Operating Systems 06 deadlock
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Deadlock (computer science)
- Wikipedia: Banker's algorithm
- Wikipedia: Priority inversion
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 8
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.
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.
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
// 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); // waitsA 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)
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
| Graph | Conclusion |
|---|---|
| No cycle | No deadlock |
| Cycle, one instance of each resource | Deadlock |
| Cycle, several instances of some resource | Possible deadlock; must check further |
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"]
| 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 |
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"]
Unsafe does not mean deadlocked; it means deadlock might happen, so the request is refused for now.
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
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.
| 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
Sources: Wikipedia: Priority inversion
- 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.
- What are the necessary conditions for deadlock? Mutual exclusion, hold and wait, no preemption, circular wait, all at the same time.
-
How do you prevent deadlock in practice? Acquire locks in a fixed global order; or use
trylockwith back-off; or hold at most one lock at a time. - 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.
- 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.
- 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.
- 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.
- 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.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look