Chapter 6: Deadlocks and Resource Allocation

Syllabus 9.3 — Resource Allocation, Deadlock Prevention, Avoidance, Detection & Recovery

1. What is a Deadlock?

A deadlock is a situation where two or more processes are permanently blocked because each is waiting for a resource held by another process. In simple words: every process is waiting, and none of them can continue.

Real-Life AnalogyComputer Example
Two people in a narrow hallway: Person A waits for B to move; Person B waits for A to move. Neither moves. P1 holds Printer, needs Scanner. P2 holds Scanner, needs Printer. Neither can continue.

2. Why Does Deadlock Occur?

Deadlocks occur because resources are limited, multiple processes compete for them, and resources are allocated in an unfortunate order.

Examples of Shared Resources
Printer, Scanner, Memory, CPU, Disk, Database, Files, Network devices

3. Necessary Conditions for Deadlock

A deadlock occurs only if all four conditions hold simultaneously. These are known as the Coffman Conditions.

ConditionDefinitionExample
1. Mutual Exclusion A resource can be used by only one process at a time One printer cannot print two jobs simultaneously
2. Hold and Wait A process holds one resource while waiting for another P1 holds Printer, waits for Scanner
3. No Preemption Resources cannot be forcibly taken away; only the owner can release them OS cannot take a printer away mid-job
4. Circular Wait Processes form a cycle of waiting P1 waits for P2, P2 waits for P3, P3 waits for P1

📌 Memory Trick — MHNC: M → Mutual Exclusion  |  H → Hold and Wait  |  N → No Preemption  |  C → Circular Wait

⚠️ If any one condition is removed, a deadlock cannot occur.


4. Resource Allocation Graph (RAG)

A graphical way to represent resource allocation and detect deadlocks.

SymbolRepresentsDirection
Circle (P1)Process—
Square [R1]Resource—
P1 → R1 (Request Edge)Process requests resourceProcess to Resource
R1 → P1 (Allocation Edge)Resource allocated to processResource to Process
Cycle in RAGConclusion
No cycleNo deadlock
Cycle exists, each resource has one instanceDeadlock exists
Cycle exists, resources have multiple instancesDeadlock possible but not guaranteed

Example: P1 → R1 → P2 → R2 → P1 — cycle exists → Deadlock.


5. Safe State

A safe state is a state in which all processes can complete in some order without causing a deadlock.

ConceptDefinition
Safe StateAt least one safe sequence exists where every process can finish
Safe SequenceAn ordering (e.g., P2 → P1 → P3) where each process can get its resources and complete
Unsafe StateNo safe sequence exists; future deadlock may occur

📌 Key Exam Statement: Every deadlock is an unsafe state, but not every unsafe state is a deadlock.

State Hierarchy
Safe State ↓ Unsafe State ↓ Deadlock

6. Banker's Algorithm

Developed by Edsger W. Dijkstra. A deadlock avoidance algorithm that allocates resources only if the system remains in a safe state.

Why “Banker”? A bank gives loans only if it can still satisfy all customers eventually. Similarly, the OS allocates resources only when safety is guaranteed.

Data StructureMeaning
AvailableCurrently available resource instances
MaxMaximum demand of each process
AllocationResources currently allocated to each process
NeedRemaining resources required: Need = Max − Allocation

Banker's Algorithm Steps

StepAction
1Calculate Need = Max − Allocation for every process
2Find a process where Need ≤ Available
3Allow that process to finish (assume it completes)
4Release its allocated resources back to Available
5Repeat until all processes finish (safe) or no candidate found (unsafe)

Worked Example

ProcessAllocationMaxNeed = Max − Alloc
P1132
P2231
P3374

Available = 3

StepActionAvailable After
1P2 Need(1) ≤ Available(3) → P2 runs and finishes3 + 2 = 5
2P1 Need(2) ≤ Available(5) → P1 runs and finishes5 + 1 = 6
3P3 Need(4) ≤ Available(6) → P3 runs and finishes6 + 3 = 9

✅ Safe sequence: P2 → P1 → P3

📌 Exam Formula: Need = Max − Allocation


7. Deadlock Handling Strategies

A. Deadlock Prevention

Prevent at least one of the four Coffman conditions from ever holding.

Condition to BreakMethod
Hold and WaitProcess must request ALL resources at once before starting
Circular WaitImpose a global ordering on resources; processes request in order
No PreemptionIf a process cannot get its next resource, release all current ones
Mutual ExclusionMake resources sharable where possible (e.g., read-only files)
AdvantagesDisadvantages
Deadlock never occursLow resource utilization; processes may wait longer

B. Deadlock Avoidance

Allow requests only when the system can remain in a safe state. Uses the Banker's Algorithm.

AdvantagesDisadvantages
Better resource utilization than preventionRequires maximum resource requirements declared in advance
No deadlockConservative — may deny safe requests

C. Deadlock Detection

Allow deadlocks to occur; periodically run a detection algorithm (RAG cycle detection) to find them.

AdvantagesDisadvantages
Simple, unrestricted resource allocationDeadlocks still occur and waste resources until detected

D. Deadlock Recovery

After detection, recover by one of:

MethodDescription
Process TerminationKill one or more deadlocked processes to break the cycle
Resource PreemptionForcibly take resources from a process and give to another
RollbackRestore a process to an earlier safe checkpoint

Strategy Comparison

MethodDeadlock Allowed?Technique
PreventionNoBreak Coffman conditions
AvoidanceNoBanker's Algorithm
DetectionYes — detect laterRAG cycle / detection algorithm
RecoveryYes — recover afterKill process / preempt resource

📌 Memory Trick — PADR: P → Prevention  |  A → Avoidance  |  D → Detection  |  R → Recovery


8. Resource Allocation

Resource allocation is the process of assigning available system resources to processes.

Resource TypeExamples
ProcessorCPU time
MemoryRAM, cache
I/O DevicesPrinter, disk, scanner
Files & NetworkFile handles, sockets
Allocation GoalDescription
Maximize utilizationKeep resources busy
Prevent deadlockAvoid circular waits
Ensure fairnessEvery process gets a turn
Improve throughputComplete more processes per unit time

9. Resource Allocation Policies

PolicyWhen AllocatedAdvantageDisadvantage
Static Allocation Before execution starts Predictable, simple Wasteful — resources held even when not in use
Dynamic Allocation During execution on demand Efficient use of resources More complex; deadlock risk

Deadlock vs Starvation vs Livelock

FeatureDeadlockStarvationLivelock
ProgressNobody movesOthers move; one waits foreverEveryone moves but no useful progress
WaitingPermanent for all involvedIndefinite for one processEndless futile activity
CauseCircular resource waitingUnfair scheduling / priorityConstant retries canceling each other
ExampleP1 waits for P2, P2 waits for P1Low-priority job never runsTwo people stepping aside for each other repeatedly

Practical Examples

ScenarioDeadlock Situation
PrinterTwo processes each hold one spool file and wait for the printer held by the other
Database TransactionsTransaction A locks Table 1, waits for Table 2. Transaction B locks Table 2, waits for Table 1.
Railway CrossingTwo trains enter opposite ends of a single-track section. Neither can move.
Bank AccountTransfer A locks account X, waits for Y. Transfer B locks account Y, waits for X.

Memory Tricks

MnemonicFull Form
Coffman Conditions — MHNC M → Mutual Exclusion   H → Hold and Wait   N → No Preemption   C → Circular Wait
Handling Strategies — PADR P → Prevention   A → Avoidance   D → Detection   R → Recovery
Banker's Formula Need = Max − Allocation

Frequently Asked Exam Questions

QuestionAnswer
Define deadlock.A situation where processes wait indefinitely for resources held by each other
State the four necessary conditions for deadlock.Mutual Exclusion, Hold and Wait, No Preemption, Circular Wait
What is a safe state?A state where all processes can complete in some order without deadlock
Who developed the Banker's Algorithm?Edsger W. Dijkstra
Key Banker's Algorithm formula?Need = Max − Allocation
Name the four deadlock handling strategies.Prevention, Avoidance, Detection, Recovery (PADR)
Difference between safe and unsafe state?Safe: safe sequence exists. Unsafe: deadlock may occur. Every deadlock is unsafe; not every unsafe is deadlock.
Which algorithm is used for deadlock avoidance?Banker's Algorithm

Chapter 6 Summary

TopicKey Point
DeadlockProcesses wait forever for resources held by each other
Coffman Conditions (MHNC)Mutual Exclusion, Hold & Wait, No Preemption, Circular Wait — all four must hold
RAGCircle = Process, Square = Resource; cycle in RAG indicates possible deadlock
Safe StateSafe sequence exists; every deadlock is unsafe, not every unsafe is a deadlock
Banker's AlgorithmAvoidance algorithm; Need = Max − Allocation
PreventionBreak one Coffman condition
AvoidanceBanker's Algorithm — keep system safe
DetectionAllow deadlocks; find them via RAG
RecoveryKill process / preempt resource / rollback

Practice MCQs

  • 1. Which condition is NOT one of the four necessary conditions for deadlock?
    A. Mutual Exclusion   B. Hold and Wait   C. Context Switching   D. Circular Wait
    ✅ Answer: C — Context Switching
  • 2. The Banker's Algorithm is used for:
    A. Deadlock Recovery   B. Deadlock Detection   C. Deadlock Avoidance   D. Scheduling
    ✅ Answer: C — Deadlock Avoidance
  • 3. Which formula is used in the Banker's Algorithm?
    A. Allocation = Need − Max   B. Need = Max − Allocation   C. Need = Available − Max   D. Max = Need − Allocation
    ✅ Answer: B — Need = Max − Allocation
  • 4. Which of the following is NOT a deadlock handling strategy?
    A. Prevention   B. Avoidance   C. Paging   D. Recovery
    ✅ Answer: C — Paging
  • 5. Which condition means a process cannot have its resources forcibly taken away?
    A. Mutual Exclusion   B. No Preemption   C. Hold and Wait   D. Circular Wait
    ✅ Answer: B — No Preemption