Deadlock
A deadlock is a state where two or more processes or threads are each waiting for a resource the other holds, so none of them can move on to the next step. This page first covers the basic concept of deadlock, then sums up the essential concepts for B4-2 issue 03 (Deadlock analysis) along with the actual test logs. After that, it looks at how the operating system prevents, avoids, detects and recovers from deadlocks, and finally compares it with the CPU issue from 02.
Deadlock Basics
Analogy: Two Cars Meeting in a Narrow Alley
What Thread A holds: resource 🔑1
What Thread A needs: resource 🔑2
What Thread B holds: resource 🔑2
What Thread B needs: resource 🔑1
Result:
Thread A: "Give me 🔑2!" → Thread B: "Give me 🔑1 first!"
Thread B: "Give me 🔑1!" → Thread A: "Give me 🔑2 first!"
→ Both wait forever... 💀 Deadlock!The 4 Conditions for Deadlock (all must hold)
1. Mutual Exclusion
→ A resource can be used by only one thread at a time
2. Hold and Wait
→ A thread waits for another resource while holding one
3. No Preemption
→ A resource cannot be taken away by force
4. Circular Wait
→ Threads wait in a cycle like A→B→C→AWhen Does Deadlock Happen
In an environment where many programs run at once, they compete for limited resources (locks, files, printers, DB rows, etc.). When a process requests a resource that another process is already using, the requester goes into the waiting state. If those waiting processes can never get back to the running state, that is a deadlock.
Time t1: Process1 gets Resource1 Process2 gets Resource2
Time t2: Process1 waits for Resource2 Process2 waits for Resource1
Process1 ──holds──▶ Resource1
▲ │
waits waits
│ ▼
Resource2 ◀──holds── Process2Each one holds the resource the other wants, so both wait endlessly. It is like two people at either end of a single-log bridge, each waiting for the other to step aside.
Essential Concepts for Deadlock Analysis
1. Multithreading
Definition: Several threads running at the same time inside one process
Process vs Thread:
Process:
- An independent unit of program execution
- Each has its own memory space
- e.g. the Chrome, YouTube and KakaoTalk apps
Thread:
- A unit of execution inside the same process
- Shares the memory space
- e.g. several tabs working at once inside Chrome
Our test:
Inside the agent-leak-app process,
├─ Worker-Thread-1
├─ Worker-Thread-2
└─ (other threads)
run at the same time2. Resource
Definition: Data or objects shared by several threads
Resources in our test:
1. Shared_Memory_A (shared memory)
2. Socket_Pool_B (socket pool)
Several threads try to access these two at the same timeReal-world example:
A bank account balance (resource):
- Thread 1: tries to deposit
- Thread 2: tries to withdraw
→ Accessing at the same time breaks consistency
→ So only 1 thread at a time may access it3. Lock (Mutual Exclusion)
Definition: A mechanism that limits a resource to being used by only 1 thread at a time
How it works:
Acquiring the lock:
Thread 1: "I'll use Shared_Memory_A" (lock acquired ✓)
Thread 2: "I'll use Shared_Memory_A" (waiting for the lock... ⏳)
Thread 1 finishes its work:
Thread 1: "I'm done" (lock released)
Thread 2: "My turn now" (lock acquired ✓)In our log:
2026-05-27 05:50:08,816 [INFO] LOCK ACQUIRED: [Shared_Memory_A]
→ This thread acquired the lock
→ Other threads cannot access it4. Deadlock
Definition: A state where 2 or more threads wait forever for resources the others hold
The situation in our test:
In time order:
T1: Thread 1 acquires resource A
Thread 2 acquires resource B
T2: Thread 1 needs resource B → Thread 2 has it → waits
Thread 2 needs resource A → Thread 1 has it → waits
T3: Neither has the resource it needs
→ waits forever (deadlock)
Log:
2026-05-27 05:50:10,820 [INFO] WAITING for [Socket_Pool_B]... (Status: BLOCKED)
2026-05-27 05:50:10,820 [INFO] WAITING for [Shared_Memory_A]... (Status: BLOCKED)
→ Both stopped in the BLOCKED stateReal-world example:
The textbook "Dining Philosophers Problem":
Philosophers A and B are seated with 2 forks
(fork 1 on A's left, fork 2 on A's right, fork 1 on B's right... etc.)
A: picks up the left fork (gets fork 1)
B: picks up the right fork (gets fork 2)
A: needs the right fork → B has it (waits)
B: needs the left fork → A has it (waits)
→ Both wait forever (nobody gets to eat)5. The 4 Deadlock Conditions
For a deadlock to happen, all 4 of the following conditions must hold:
Condition 1: Mutual Exclusion
The resource is used exclusively
= only 1 thread can use it at a time
Our case:
Shared_Memory_A can be accessed by only 1 thread at a time
Socket_Pool_B can also be accessed by only 1 thread at a time
✓ HoldsCondition 2: Hold and Wait
A thread holds a resource while waiting for another
= it keeps what it has and waits for what it needs
Our case:
Thread 1: holds resource A → waits for resource B
Thread 2: holds resource B → waits for resource A
✓ HoldsCondition 3: No Preemption
A resource cannot be taken away by force
= only the thread that acquired it can release it
Our case:
Once Thread 1 has resource A,
no other thread can take it away by force
(they wait until Thread 1 releases it)
✓ HoldsCondition 4: Circular Wait
Waiting for resources forms a cycle
= A → B → A (or A → B → C → A, etc.)
Our case:
Thread 1 (holds resource A) → Thread 2 (holds resource B) → Thread 1
↑ ↓
└──────────────────────────────┘
A cycle!
✓ HoldsConclusion: All 4 conditions hold → deadlock occurs
6. Resource Ordering
Definition: The order in which resources are acquired when several are used
The problem (our test):
Thread 1: acquires resource A → resource B
Thread 2: acquires resource B → resource A
↑
a different order!Solution:
All threads acquire in the same order:
Option 1:
Thread 1: resource A → resource B
Thread 2: resource A → resource B (same order)
Option 2:
Thread 1: resource B → resource A
Thread 2: resource B → resource A (same order)
→ Circular wait becomes impossible!7. Blocking vs Waiting
Blocking:
A thread stops executing while it waits for a resource
In the log:
[INFO] WAITING for [Socket_Pool_B]... (Status: BLOCKED)
→ BLOCKED state = not executing, waitingCPU/memory state:
A thread in the BLOCKED state:
- CPU: 0% (not executing)
- Memory: no change (no new allocations)
- Logs: none (no I/O performed)Our test result:
After 2026-05-27 05:50:10,820:
- CPU: 0%
- Memory: flat
- Logs: none
→ All threads in the BLOCKED stateRecap: Deadlock (Issue 03)
Thread 1: acquires resource A → waits for resource B
Thread 2: acquires resource B → waits for resource A
→ Each waits forever for the other's resource
→ All 4 deadlock conditions hold
→ Process freezes (unresponsive)
Conclusion: Dangerous! Switch to MULTI_THREAD=false immediatelyHow to Deal With Deadlock
A deadlock only happens when all 4 conditions above hold. So the ways to handle it fall broadly into "stop it from ever happening" and "find it and break it when it does."
| Approach | When it acts | One-line summary | Cost |
|---|---|---|---|
| Prevention | In advance | Block one of the 4 conditions at the source | Wastes a lot of resources |
| Avoidance | Every time a resource is granted | Check whether granting is safe and refuse if risky | Checking cost every time; maximum needs must be known in advance |
| Detection & Recovery | After it happens | Allow deadlock, then find and break it | Cost of running the detection algorithm, lost work |
| Ignore | Never | It is rare, so leave it and restart if it happens | Cheapest. What typical general-purpose operating systems actually do |
Prevention: Remove One Condition
| Condition to remove | Method | Drawback |
|---|---|---|
| Mutual exclusion | Let several processes share the resource | Many resources, like printers and locks, must be used by one at a time, so this is hard in practice |
| Hold and wait | Have a process receive all the resources it needs at once before running | Holds even resources it does not need yet (waste); processes that cannot get all of them starve |
| No preemption | If a process must wait for another resource, make it release what it holds | Loss from having to roll back work in progress |
| Circular wait | Number every resource and allow requests only in number order | To follow the numbering, a resource may have to be grabbed early |
The uniform resource ordering seen above is exactly the prevention method that removes circular wait. It is also the method used most in practice.
Avoidance: Grant Only When It Is Safe
Avoidance checks in advance, every time a resource is requested, "After granting this, is there still an order in which every process can eventually finish?" A state where such an order (a safe sequence) exists is called a safe state, and resources are granted only while the safe state holds. Leaving the safe state does not mean a deadlock will definitely happen, but it means one could, so the request is not granted and the process waits.
Banker's Algorithm
The name comes from a bank that lends money only when the cash it has can eventually satisfy every customer's loan needs. Each process must declare up front the maximum number of resources it will use.
- Need (amount still needed) = maximum need - amount already received
- Find a process whose Need can be met with the remaining resources, assume it runs to completion, and take back the resources it held.
- If repeating this lets every process finish, the state is safe.
# Banker's algorithm: check whether the current state is a "safe state"
available = [3, 3, 2] # remaining resources (A, B, C)
allocation = {"P0": [0, 1, 0], "P1": [2, 0, 0], "P2": [3, 0, 2], "P3": [2, 1, 1], "P4": [0, 0, 2]}
maximum = {"P0": [7, 5, 3], "P1": [3, 2, 2], "P2": [9, 0, 2], "P3": [2, 2, 2], "P4": [4, 3, 3]}
need = {p: [m - a for m, a in zip(maximum[p], allocation[p])] for p in allocation}
work = available[:]
order = []
while len(order) < len(allocation):
for p in allocation:
if p not in order and all(n <= w for n, w in zip(need[p], work)):
work = [w + a for w, a in zip(work, allocation[p])] # when done, return the borrowed resources
order.append(p)
print(f"{p} can run (needs {need[p]}) → remaining after return {work}")
break
else:
print("No more processes can run → unsafe state")
break
else:
print("Safe sequence:", " → ".join(order))P1 can run (needs [1, 2, 2]) → remaining after return [5, 3, 2]
P3 can run (needs [0, 1, 1]) → remaining after return [7, 4, 3]
P0 can run (needs [7, 4, 3]) → remaining after return [7, 5, 3]
P2 can run (needs [6, 0, 0]) → remaining after return [10, 5, 5]
P4 can run (needs [4, 3, 1]) → remaining after return [10, 5, 7]
Safe sequence: P1 → P3 → P0 → P2 → P4The remaining resources (3, 3, 2) cannot satisfy P0 (7, 4, 3) right away, but finishing P1 first and taking its resources back eventually lets everyone finish, so this is a safe state.
Resource-Allocation Graph Algorithm
This decides using a graph that draws processes and resources as nodes, and "requests" and "holds" as arrows.
- When a process requests a resource, check whether turning that request arrow into an allocation arrow creates a cycle (a loop) in the graph.
- If no cycle forms, grant the resource.
- A cycle does not always mean deadlock.
- If each resource has only one instance, cycle = deadlock
- If resources have several instances, cycle = possible deadlock (it may clear when another process returns resources)
Detection and Recovery: Find It and Break It
Deadlocks are allowed to happen, and a detection algorithm runs periodically (or on every resource request) to find them. It looks for cycles in the resource-allocation graph or uses a calculation similar to the banker's algorithm. Running it more often finds deadlocks sooner but adds more overhead.
Once one is found, it is broken in one of two ways.
- Terminate processes
- Terminate all deadlocked processes at once (certain, but a lot of work is lost)
- Terminate them one at a time until the deadlock clears (the detection algorithm must run again after each termination)
- Preempt resources
- Take resources from a deadlocked process and give them to another (the process that lost them is paused)
- Take first from processes with lower priority or that have run less so far. If the same process keeps being the victim, it starves, so the number of times it has been chosen is also considered
Databases are a typical example. When transactions deadlock each other, the DB detects it and rolls back one of the transactions. It is worth reading Concurrency Problems and Isolation Levels as well.
The Dining Philosophers Problem
Five philosophers sit at a round table, with one chopstick between each pair, five in total. To eat, a philosopher needs both chopsticks on either side.
Philosopher0 ─ Chopstick0 ─ Philosopher1 ─ Chopstick1 ─ Philosopher2
│ │
Chopstick4 Chopstick2
│ │
Philosopher4 ─────────── Chopstick3 ─────────── Philosopher3
(The round table drawn flat. Each philosopher needs the 2 chopsticks on either side)If everyone at the same moment "picks up the left chopstick first, then waits for the right," all five end up holding just the left one and waiting forever. It is a classic example that contains all 4 deadlock conditions. Even if deadlock is avoided, some philosopher may never manage to grab chopsticks and go hungry, so it also comes up when explaining starvation.
Here are the solutions.
- Let at most 4 of the 5 philosophers sit at once. If 4 people share 5 chopsticks, at least one can get 2.
- Let a philosopher pick up chopsticks only when both can be picked up. (Removes hold and wait)
- Have one philosopher (or the even-numbered ones) pick up the right chopstick first. This breaks the circular-wait loop.
Interview Questions
- What is a deadlock, and what are its 4 conditions?
- How do deadlock prevention and deadlock avoidance differ?
- Explain the banker's algorithm.
- Explain the dining philosophers problem and how to solve it.
- How do deadlock and starvation differ? (In a deadlock, everyone involved is stuck; in starvation, other processes run fine but one particular process keeps missing its turn)
CPU Issue vs Deadlock
| Item | CPU (Issue 02) | Deadlock (Issue 03) |
|---|---|---|
| Problem | CPU overuse | Resource contention |
| Fix | Cooldown (automatic adjustment) | Uniform resource ordering |
| Process state | Keeps running (lowers CPU) | Frozen (BLOCKED) |
| CPU utilization | Stays at 30% | 0% (frozen) |
| Logs | Keep coming | Stop |
| Automatic recovery | ✓ Yes | ✗ No |
| Risk | Low (it is controlled) | High (waits forever) |
Summary
Deadlock Concepts
- Multithreading: Several threads running at once inside one process
- Resource: Data/objects shared by several threads
- Lock: Limits access to 1 thread at a time
- Deadlock: A state where 2 or more threads wait forever for each other's resources
- The 4 deadlock conditions: Mutual Exclusion, Hold and Wait, No Preemption, Circular Wait
- Resource ordering: All threads acquire resources in the same order
Ways to Handle Deadlock
| Concept | Plain-language summary |
|---|---|
| Prevention | Make one of the 4 conditions impossible (e.g. a uniform order for grabbing resources) |
| Avoidance | Before granting a resource, check "can everyone still finish if I grant this?" |
| Banker's algorithm | Lend only when the remaining money can eventually satisfy every customer |
| Detection & Recovery | Let it happen, then when found, end processes or take resources away to break it |
| Dining philosophers | A deadlock example where everyone grabs the left chopstick first and they all go hungry |
| Starvation | The system keeps running, but one particular job keeps missing its turn |
Study Tip: Understanding Deadlock
- What if there are several threads? (= Multithreading)
- What if they share resources? (= protect them with a Lock)
- What if they acquire them in different orders? (= Deadlock risk!)
- What if one thread freezes? (= the other threads freeze too)
Source: Codyssey-B1/B4-2
