Chapter 04 · OS
Process Synchronization & Deadlocks
6 topics · 2 sections · beginner-friendly study notes · Updated
Detailed notes with diagrams
A full topic lesson from this chapter — diagram, table, examples and a quick check.
When processes share data, uncontrolled interleaving causes race conditions.
This chapter covers the critical-section problem, mutex locks and semaphores, the producer-consumer pattern, the four deadlock conditions, and handling deadlocks by prevention, avoidance (Banker’s algorithm) and detection.
Semaphore programs and Banker’s safe-sequence numericals are staple GATE questions.
Database locking, multithreaded servers, kernel locking, avoiding hangs in concurrent programs.
Race Conditions & Critical Section
A race condition occurs when the result depends on the order in which concurrent processes access shared data. A critical section is code that accesses shared resources; a correct solution must give mutual exclusion, progress and bounded waiting.
In short: Two people editing the same bank balance at once can lose an update; only one at a time may be in the critical section.
Think about it
Shared mutable state without synchronization leads to rare, hard-to-reproduce bugs.
Example
counter++ compiles to load, add, store.
If two threads both load 5, both store 6, one increment is lost.
Requirements
- 1Mutual exclusion: at most one process in its critical section;
- 2Progress: if no one is in the critical section, the choice of who enters cannot be postponed indefinitely and only processes wanting to enter take part in the decision;
- 3Bounded waiting: a limit on how many times others may enter after a process has requested entry.
Software solutions (Peterson’s algorithm for two processes) and hardware support (atomic test-and-set, compare-and-swap) both exist.
Disabling interrupts works only on a single processor and is unsafe for user code.
Key points
- Critical section: Code segment that must not be executed concurrently by multiple processes.
- Atomic operation: Operation that completes without interruption.
- Busy waiting: Repeatedly checking a condition while holding the CPU (spinlock).
- Race example: two threads each run counter++ 1000 times on counter = 0
→final value can be anywhere from 1000 to 2000 (not necessarily 2000). - A correct solution needs mutual exclusion, progress and bounded waiting; no assumption about relative speeds of processes.
Example
CodeLost update and the general critical-section structure:
/* counter++ is NOT atomic: load, add, store */
int counter = 5;
/* T1: R1 = counter (5) T2: R2 = counter (5)
T1: R1 = R1 + 1 (6) T2: R2 = R2 + 1 (6)
T1: counter = R1 (6) T2: counter = R2 (6) -> one increment lost, expected 7 */
do {
/* entry section */
/* critical section: access shared data */
/* exit section */
/* remainder section */
} while (true);Peterson Solution & Mutex
Peterson's solution is a software algorithm giving mutual exclusion, progress and bounded waiting for exactly two processes using a shared flag[2] array (intention to enter) and a shared turn variable (whose turn to yield). A mutex lock is the OS/hardware-backed primitive with acquire() and release() so that only one thread at a time is inside the critical section.
In short: Peterson: "I want to go in, but you go first if you also want to" — whoever politely sets turn last waits. A mutex is a single key to the room.
Think about it
GATE repeatedly asks whether a given two-process entry protocol satisfies mutual exclusion, progress and bounded waiting; Peterson's is the model answer.
Process i (j = 1 − i): flag[i] = true; turn = j; while (flag[j] && turn == j) ; critical section; flag[i] = false.
Why it works
if both want to enter, both set flag true, and turn ends up as whichever process wrote it last; that process loops while the other proceeds; so exactly one enters (mutual exclusion).
A process that does not want to enter has flag false so the other is not blocked (progress).
A process waits at most one entry of the other because after exit it sets flag false or, if it re-enters, sets turn to the other (bounded waiting).
Limits
- 1only two processes
- 2uses busy waiting
- 3on modern CPUs with reordering/caches it needs memory barriers, so real systems use hardware atomics.
Hardware support
test-and-set (atomically read and set a lock to true, returns old value), compare-and-swap, and atomic exchange build spinlocks: while (test_and_set(&lock)) ; ...
lock = false.
Mutex (mutual exclusion lock): acquire() blocks (or spins) until available; release() unlocks.
Properties: ownership (only the locking thread may unlock), non-recursive by default, may use priority inheritance.
Spinlock vs sleeping mutex: spin when the critical section is shorter than a context switch and on multiprocessors; sleep otherwise.
Peterson's with the two statements swapped (turn = j before flag[i] = true) breaks mutual exclusion — a favourite trap.
Key points
- flag[] / turn: Peterson variables: intention to enter and whose turn it is to yield.
- Test-and-set: Atomic instruction that returns the old value of a lock and sets it to true.
- Spinlock: Lock that busy-waits in a loop instead of blocking.
- Mutex: Lock with ownership: acquire before, release after the critical section.
- Peterson satisfies mutual exclusion, progress and bounded waiting for 2 processes.
- Simple "turn" alone gives strict alternation: mutual exclusion yes, progress NO. Simple "flag" alone: mutual exclusion yes, but deadlock possible if both set flags together.
Example
CodePeterson, test-and-set and pthread mutex:
/* Peterson's solution, processes i and j (j = 1 - i) */
bool flag[2] = {false, false};
int turn;
void enter(int i) {
int j = 1 - i;
flag[i] = true; // I want to enter
turn = j; // but you may go first
while (flag[j] && turn == j) ; // busy wait
}
void leave(int i) { flag[i] = false; }
/* Hardware spinlock using test-and-set */
bool lock = false;
void acquire(void) { while (test_and_set(&lock)) ; }
void release(void) { lock = false; }
/* POSIX mutex */
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&m); /* critical section */ pthread_mutex_unlock(&m);Counting vs Binary Semaphores
A semaphore is an integer variable accessed only through atomic wait (P, decrement and block if negative/zero) and signal (V, increment and wake a waiter). A binary semaphore takes only the values 0 and 1 and gives mutual exclusion or signalling; a counting semaphore has an unrestricted value initialised to the number of available resource instances.
In short: Mutex is a single key to a room. A counting semaphore is a pool of N identical keys.
Think about it
Semaphores are the standard OS-level tool to build every higher synchronization pattern.
Binary semaphore (0/1) behaves like a mutex, except a mutex has an owner and must be released by the same thread while a semaphore can be signalled by another process (useful for ordering).
Counting semaphore initialised to the number of available instances controls a resource pool.
Implementation with a waiting queue avoids busy waiting: wait blocks the caller, signal moves a blocked process to ready.
Typical uses
mutual exclusion (initial value 1) and ordering/synchronization (initial value 0, one process waits for an event another signals).
Errors: swapping wait and signal breaks mutual exclusion; two wait calls on the same semaphore in sequence can deadlock.
Spinlocks suit very short critical sections on multiprocessors.
Key points
wait(S)/ P: Decrement S; block if no resource is available.signal(S)/ V: Increment S; wake a waiting process if any.- Monitor: High-level construct giving mutual exclusion plus condition variables.
- Binary semaphore: initial 1 for mutual exclusion, initial 0 for event/ordering. Counting semaphore: initial n = number of identical resources (e.g. 3 printers
→S = 3). - Semaphore value negative
→its magnitude equals the number of blocked processes (in the classic definition). - If S is initialised to n (counting), n processes can pass wait before the next one blocks.
Read more
Example
CodeS = 1 (binary), P1 does wait(S) then P2 does wait(S): P2 blocks (S = −1 in the classic definition); after signal(S) by P1, P2 resumes. A binary semaphore can be built from counting semaphores and vice versa.
Classical IPC Problems
The classical synchronization problems are the bounded-buffer (producer-consumer) problem, the readers-writers problem and the dining philosophers problem. In producer-consumer, producers insert items into a buffer of size N and consumers remove them; the buffer must not overflow, not underflow, and its updates must be mutually exclusive.
In short: A conveyor belt with limited slots: producers wait when full, consumers wait when empty.
Use three semaphores: empty = N (free slots), full = 0 (filled slots), mutex = 1 (protect buffer).
Order matters
if the producer does wait(mutex) before wait(empty) and the buffer is full, it holds the mutex while sleeping and the consumer can never enter, so deadlock occurs.
Related classics
readers-writers (reader preference can starve writers) and dining philosophers (circular wait on forks).
Key points
- Bounded buffer: Fixed-size shared buffer between producer and consumer.
- Underflow / overflow: Removing from empty / inserting into full buffer.
- Readers-writers (reader preference): semaphores mutex = 1 (protects read_count), wrt = 1 (writers/first-last reader). Reader: wait(mutex); read_count++; if (read_count
==1)wait(wrt); signal(mutex); READ; wait(mutex); read_count--; if (read_count==0)signal(wrt); signal(mutex). Writer:wait(wrt); WRITE;signal(wrt). Many readers may read together; a writer needs exclusive access; writers can starve. - Dining philosophers: 5 philosophers, 5 forks (semaphore fork[5] = 1). Naive:
wait(fork[i]);wait(fork[(i+1)%5]); eat→if all pick up the left fork at once, circular wait = deadlock. Fixes: allow at most 4 philosophers at the table, pick both forks only if both are free (inside a critical section), or make one philosopher pick the right fork first (asymmetric / resource ordering). - Semaphores needed for bounded buffer: 3 (mutex, empty, full). Producer-consumer with buffer size N: empty starts at N, full at 0.
Example
CodeSemaphore solution:
semaphore mutex = 1, empty = N, full = 0;
producer() {
while (true) {
item = produce();
wait(empty); // wait for a free slot
wait(mutex); // enter critical section
insert(item);
signal(mutex);
signal(full); // one more filled slot
}
}
consumer() {
while (true) {
wait(full); // wait for an item
wait(mutex);
item = remove();
signal(mutex);
signal(empty); // one more free slot
consume(item);
}
}Deadlock & 4 Coffman Conditions
A deadlock is a state where each process in a set waits for a resource held by another in the set, so none can proceed. It requires all four conditions: mutual exclusion, hold and wait, no preemption, and circular wait.
In short: Two cars on a one-lane bridge from opposite sides: each waits for the other to back up.
Think about it
Understanding the four conditions tells you which one to break.
Resource-allocation graph (RAG): request edge P→R, assignment edge R→P. With single-instance resources a cycle implies deadlock (necessary and sufficient).
With multiple instances a cycle is necessary but not sufficient.
Deadlock vs starvation: in deadlock the waiting is circular and permanent; starvation is indefinite postponement while others progress.
Strategies: ignore (ostrich algorithm used by Unix/Windows for most resources), prevention, avoidance, detection and recovery.
Key points
- Hold and wait: Process holds some resources while requesting more.
- Circular wait: P0 waits for P1, P1 for P2, …, Pn for P0.
- Wait-for graph: RAG simplified to process-to-process edges for single-instance resources.
- Deadlock needs ALL four conditions; removing any one prevents it.
Banker's Algorithm
Prevention negates at least one necessary condition by design. Avoidance (Banker’s algorithm) grants a request only if the system stays in a safe state. Detection allows deadlock, then finds it with a graph or matrix algorithm and recovers.
In short: Prevention builds rules so deadlock cannot occur; avoidance checks before each grant; detection cleans up after.
Think about it
Banker’s algorithm is the standard avoidance technique and a guaranteed numerical in exams.
Prevention
eliminate hold-and-wait (request all at once or release before requesting; hurts utilization), allow preemption, impose a total ordering on resource types and request in increasing order (breaks circular wait; most practical).
Safe state: there exists a sequence of all processes such that each can finish with the available plus resources released by earlier ones.
Unsafe does not mean deadlocked but may lead to it.
Banker’s data: Available, Max, Allocation and Need = Max - Allocation.
Safety algorithm: Work = Available; repeatedly find an unfinished process with Need ≤ Work, add its Allocation to Work and mark it finished; if all finish, the state is safe.
Resource-request algorithm: if Request ≤ Need and Request ≤ Available, pretend to allocate and run safety; grant only if safe.
Detection uses the same idea with Request matrix instead of Need.
Recovery: terminate processes (all or one by one) or preempt resources with rollback while avoiding starvation of the same victim.
Key points
- Safe state: A state with at least one safe sequence.
- Need matrix: Max - Allocation: what each process may still request.
- Ostrich algorithm: Ignore deadlocks, assuming they are rare.
- Complexity of the safety algorithm:
O(m·n²)for n processes and m resource types.
Read more
Solved examples
Banker’s algorithm: 5 processes P0-P4, resource types A, B, C with totals (10, 5, 7). Allocation: P0 (0,1,0), P1 (2,0,0), P2 (3,0,2), P3 (2,1,1), P4 (0,0,2). Max: P0 (7,5,3), P1 (3,2,2), P2 (9,0,2), P3 (2,2,2), P4 (4,3,3). Is the system safe?
- Total = (10,5,7)
- Sum of allocation = (7,2,5)
- Available = (3,3,2)
Need matrix and a safe sequence
Formula Applied:—Approach note: Always list Need first. Several safe sequences may exist; any valid one is accepted unless a specific order is asked.
Continuing example above: P1 requests (1,0,2). Can it be granted immediately?
- Available = (3,3,2)
- P1 Need = (1,2,2)
- P1 Allocation = (2,0,0)
Grant or deny
Formula Applied:—Approach note: Three checks: Request ≤ Need, Request ≤ Available, then safety test on the tentative state.
Semaphore S = 3 initially. Five processes each call wait(S) once and none call signal. How many processes block?
Number of blocked processes
Formula Applied:—Approach note: Blocked = number of waits - initial value (when positive).
Four cars approach a four-way stop and each waits for the car on its right forever. Name the deadlock condition illustrated.
Condition name
Formula Applied:—Approach note: Break circular wait with a total ordering on resources.
Real-world applications
Using Process Synchronization & Deadlocks in real projects
Database locking, multithreaded servers, kernel locking, avoiding hangs in concurrent programs.
Common mistakes
❌ Myth: An unsafe state means a deadlock has already occurred.
Why this is wrong: Unsafe means no safe sequence is guaranteed; processes may still happen to finish.
✅ Verified Truth: Deadlock states are unsafe, but not all unsafe states are deadlocks.
⚠️ Exam Tip: Remember: deadlock ⊂ unsafe.
❌ Myth: A cycle in a resource-allocation graph always means deadlock.
Why this is wrong: With multiple instances of a resource type, another process may release an instance and break the cycle.
✅ Verified Truth: Cycle ⇒ deadlock only if each resource type has a single instance.
⚠️ Exam Tip: Check instance counts before answering.
❌ Myth: A binary semaphore and a mutex are exactly the same thing.
Why this is wrong: A mutex has ownership and must be unlocked by the thread that locked it; a semaphore can be signalled by any process.
✅ Verified Truth: Similar for mutual exclusion, but semaphores also serve for signalling and ordering.
⚠️ Exam Tip: Mention ownership as the key difference.
Revision notes
When processes share data, uncontrolled interleaving causes race conditions. This chapter covers the critical-section problem, mutex locks and semaphores, the producer-consumer pattern, the four deadlock conditions, and handling deadlocks by prevention, avoidance (Banker’s algorithm) and detection.
High-Yield Quick Revision Points
- Critical section: mutual exclusion, progress, bounded waiting
- wait = P (decrement, block), signal = V (increment, wake)
- Producer-consumer: empty=N, full=0, mutex=1; wait(mutex) after the counting semaphore
- Deadlock needs mutual exclusion + hold&wait + no preemption + circular wait
- Need = Max - Allocation; safe if a full sequence exists
- Min resources for no deadlock: sum(max_i - 1) + 1
Practice questions
Which is NOT one of the four necessary conditions for deadlock?
A system has 3 processes each needing 2 units of a single resource type. Minimum number of units that guarantees no deadlock?
In Banker’s algorithm, Need is computed as:
In the producer-consumer solution, interchanging wait(empty) and wait(mutex) in the producer can cause:
Imposing a total order on resource types and requesting them in that order prevents: