Operating System
Comprehensive exam revision notes for BCA-205N Unit 4 (Process Synchronization, Concurrency & Deadlocks). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.
Operating System
Process Synchronization, Concurrency & Deadlocks
Core Definitions & Key Concepts
The Critical Section Problem in concurrent programming
A Critical Section is a code segment in a multi-process or multi-threaded program that accesses shared resources (such as shared variables, tables, or files). The critical section problem is to design an execution protocol ensuring that when one process is executing inside its critical section, no other process is allowed to execute inside its critical section.
State the three mandatory criteria for any valid Critical Section solution
- Mutual Exclusion: If process P_i is executing in its critical section, no other process can be executing in its critical section.
- Progress: If no process is executing in its critical section and some processes wish to enter, only those processes not executing in their remainder sections can participate in deciding who enters next, and this selection cannot be postponed indefinitely.
- Bounded Waiting: A bound must exist on the number of times other processes are allowed to enter their critical sections after a process has made a request to enter and before that request is granted.
Counting Semaphores and Binary Semaphores (Mutexes)
A Binary Semaphore (Mutex) has an integer value restricted strictly to 0 or 1, primarily used to enforce mutual exclusion across shared resources.
A Counting Semaphore can take any non-negative integer value over an unrestricted domain, primarily used to manage finite pools of multiple identical resource instances (e.g., a buffer pool with N slots).
Deadlock and state the four Coffman Conditions
A Deadlock is a state where a set of processes are permanently blocked because each process holds resources and waits for other resources held by other processes in the same set. Four Necessary Coffman Conditions:
- Mutual Exclusion: At least one non-sharable resource held.
- Hold and Wait: A process holds resources while requesting additional resources.
- No Preemption: Resources cannot be forcibly seized; only voluntarily released.
- Circular Wait: A closed cycle of processes exists: P_0 \to P_1 \to \dots \to P_n \to P_0.
What is the difference between Deadlock Prevention and Deadlock Avoidance
Deadlock Prevention statically imposes system-wide constraints on resource requests to invalidate at least one of the four Coffman conditions, often degrading resource utilization. Deadlock Avoidance dynamically examines every resource request at runtime using advance knowledge of maximum resource demands (e.g., Banker's Algorithm) to ensure the system never transitions into an unsafe state.
What is a Safe State in deadlock management
A system state is Safe if there exists at least one Safe Sequence \langle P_1, P_2, \dots, P_n \rangle such that for every process P_i, the maximum resources it may still request can be satisfied by the currently available resources plus the resources already held by all preceding processes P_j (where j < i).
Conceptual & Architectural Analysis
Present Peterson's Algorithm for two-process mutual exclusion and prove its correctness
Peterson's Algorithm (Software Solution for Two Processes)
Peterson's Algorithm guarantees mutual exclusion, progress, and bounded waiting for two processes (P_0 and P_1) using shared variables:
1int turn; // Indicates whose turn it is to enter CS2boolean flag[2]; // flag[i] = true indicates Pi is ready to enter CSProcess Structure for P_i (where j = 1 - i):
1do {2 flag[i] = true; // Declare intent to enter3 turn = j; // Generously yield initial turn to competitor4 5 // Entry Section: Busy-wait while competitor wants in AND has turn6 while (flag[j] && turn == j);7
8 // CRITICAL SECTION9 /* Shared resource access occurs here */10
11 // Exit Section12 flag[i] = false; // Relinquish access13
14 // REMAINDER SECTION15} while (true);Correctness Proof:
- Mutual Exclusion: For both P_0 and P_1 to be in their Critical Sections simultaneously, both
flag[0] == trueandflag[1] == true. But the variableturncan hold only one scalar value (0or1) at any single point in time. Ifturn == 0, P_1 loops in itswhile; ifturn == 1, P_0 loops. Hence, mutual exclusion is strictly preserved. - Progress: If P_1 does not wish to enter,
flag[1] == false, so P_0'swhilecondition immediately evaluates to false, allowing P_0 to enter without delay. - Bounded Waiting: Once P_0 sets
turn = 1, it cannot overwriteturnagain until it finishes its critical section. Thus, P_1 is guaranteed entry after at most one wait cycle.
The Producer-Consumer Bounded-Buffer Problem and its solution using Semaphores
Producer-Consumer (Bounded Buffer) Synchronization
System Setup:
- A shared circular buffer of fixed size N.
- A Producer process creates data items and places them in the buffer.
- A Consumer process removes items from the buffer and consumes them.
Semaphores Employed:
mutex = 1(Binary Semaphore ensuring mutually exclusive buffer access).empty = N(Counting Semaphore tracking empty slots available).full = 0(Counting Semaphore tracking filled slots available).
1// PRODUCER PROCESS // CONSUMER PROCESS2do { do {3 // Produce item 'x' wait(full); // Wait if buffer empty4 wait(empty); // Wait if buffer full wait(mutex); // Lock buffer5 wait(mutex); // Lock buffer6 7 // Add item 'x' to buffer // Remove item 'y' from buffer8 buffer[in] = x; y = buffer[out];9 in = (in + 1) % N; out = (out + 1) % N;10 11 signal(mutex); // Unlock buffer signal(mutex); // Unlock buffer12 signal(full); // Increment filled signal(empty); // Increment empty13 14} while (true); } while (true);- Race Condition Prevention: The
mutexensures only one process writes to or reads from the buffer at any instant. - Buffer Overflow & Underflow Prevention:
wait(empty)blocks the producer when buffer is full (empty = 0), andwait(full)blocks the consumer when buffer is empty (full = 0).
Resource Allocation Graphs (RAG) and how cycles correlate with deadlocks
Resource Allocation Graph (RAG) Analysis
A Resource Allocation Graph is a directed bipartite graph G = (V, E) where:
- Vertices V are partitioned into Processes P = \{P_1, P_2, \dots, P_n\} (circles) and Resource Types R = \{R_1, R_2, \dots, R_m\} (rectangles containing dots for multiple instances).
- Edges E:
- Request Edge ($P_i \to R_j$): Directed from process to resource type.
- Assignment Edge ($R_j \to P_i$): Directed from a resource instance dot to process.
( P1 ) -----------------------> [ R1 (•) ]
^ |
| v
[ R2 (•) ] <----------------------- ( P2 )Cycle vs Deadlock Decision Rules:
- Single Instance per Resource Type: A cycle in the graph is a necessary AND sufficient condition for deadlock. If a cycle exists, the system is deadlocked.
- Multiple Instances per Resource Type: A cycle is a necessary but NOT sufficient condition. If a cycle exists, a deadlock may exist, but if external processes holding instances outside the cycle can terminate and release resources, the cycle can break naturally without deadlock.
In-Depth Analysis & Implementation
Solve the Banker's Algorithm problem: Consider 5 processes (P0 to P4) and 3 resource types (A, B, C) with total system instances A=10, B=5, C=7. Given the Allocation and Max matrices below, determine: (1) Is the system in a safe state? Find the safe sequence. (2) If a request from P1 arrives for (1, 0, 2), can the request be granted immediately
Comprehensive Numerical: Dijkstra's Banker's Algorithm
System Configuration:
- Total Resource Instances: A = 10, B = 5, C = 7
Current State Tables:
| Process | Allocation (A B C) | Max (A B C) |
|---|---|---|
| P_0 | 0 1 0 | 7 5 3 |
| P_1 | 2 0 0 | 3 2 2 |
| P_2 | 3 0 2 | 9 0 2 |
| P_3 | 2 1 1 | 2 2 2 |
| P_4 | 0 0 2 | 4 3 3 |
Step 1: Calculate Need Matrix and Initial Available Vector
$Need[i] = Max[i] - Allocation[i]$
| Process | Allocation | Max | Need = Max - Allocation |
|---|---|---|---|
| P_0 | 0 1 0 | 7 5 3 | 7 4 3 |
| P_1 | 2 0 0 | 3 2 2 | 1 2 2 |
| P_2 | 3 0 2 | 9 0 2 | 6 0 0 |
| P_3 | 2 1 1 | 2 2 2 | 0 1 1 |
| P_4 | 0 0 2 | 4 3 3 | 4 3 1 |
$Total Allocated = (0+2+3+2+0, 1+0+0+1+0, 0+0+2+1+2) = (7, 2, 5) Available = Total - Allocated = (10-7, 5-2, 7-5) = \mathbf{(3, 3, 2)}$
Step 2: Safety Algorithm Execution
Initialize: Work = (3, 3, 2), Finish[i] = False for all i.
- Check $P_0$: Need (7, 4, 3) ≤ Work (3, 3, 2)? No. (P_0 must wait).
- Check $P_1$: Need (1, 2, 2) ≤ Work (3, 3, 2)? Yes.
- P_1 executes and finishes.
- Work = Work + Alloc(P_1) = (3, 3, 2) + (2, 0, 0) = \mathbf{(5, 3, 2)}.
- Finish[P_1] = True.
- Check $P_3$: Need (0, 1, 1) ≤ Work (5, 3, 2)? Yes.
- P_3 executes and finishes.
- Work = (5, 3, 2) + (2, 1, 1) = \mathbf{(7, 4, 3)}.
- Finish[P_3] = True.
- Check $P_4$: Need (4, 3, 1) ≤ Work (7, 4, 3)? Yes.
- P_4 executes and finishes.
- Work = (7, 4, 3) + (0, 0, 2) = \mathbf{(7, 4, 5)}.
- Finish[P_4] = True.
- Check $P_0$: Need (7, 4, 3) ≤ Work (7, 4, 5)? Yes.
- P_0 executes and finishes.
- Work = (7, 4, 5) + (0, 1, 0) = \mathbf{(7, 5, 5)}.
- Finish[P_0] = True.
- Check $P_2$: Need (6, 0, 0) ≤ Work (7, 5, 5)? Yes.
- P_2 executes and finishes.
- Work = (7, 5, 5) + (3, 0, 2) = \mathbf{(10, 5, 7)}.
- Finish[P_2] = True.
Conclusion for Part (1): All processes finish. The system is in a SAFE STATE. Safe Sequence: \mathbf{\langle P_1, P_3, P_4, P_0, P_2 \rangle} (or \langle P_1, P_3, P_0, P_2, P_4 \rangle).
Step 3: Handling Resource Request: P_1 requests (1, 0, 2)
- Check: Request_1 (1, 0, 2) ≤ Need_1 (1, 2, 2)? Yes.
- Check: Request_1 (1, 0, 2) ≤ Available (3, 3, 2)? Yes.
- Temporarily allocate resources to P_1:
- Available' = (3, 3, 2) - (1, 0, 2) = \mathbf{(2, 3, 0)}
- Allocation_1' = (2, 0, 0) + (1, 0, 2) = \mathbf{(3, 0, 2)}
- Need_1' = (1, 2, 2) - (1, 0, 2) = \mathbf{(0, 2, 0)}
- Run Safety Algorithm on modified state with Work = (2, 3, 0):
- P_1: Need (0, 2, 0) ≤ (2, 3, 0)? Yes!
- Work = (2, 3, 0) + (3, 0, 2) = \mathbf{(5, 3, 2)}.
- Now with Work = (5, 3, 2), P_3 can finish \to Work = (7, 4, 3), then P_4, P_0, P_2 can finish exactly as before.
Conclusion for Part (2): A safe sequence \langle P_1, P_3, P_4, P_0, P_2 \rangle exists. Therefore, the request from $P_1$ can be GRANTED IMMEDIATELY.
Analyze Classical Concurrency Problems: Describe the Dining Philosophers Problem and the Readers-Writers Problem. Discuss starvation issues and present deadlock-free solutions for each
Classical Synchronization Problems
1. The Dining Philosophers Problem
Five philosophers sit around a circular table with 5 chopsticks (chopsticks 0 to 4). Each philosopher alternates between thinking and eating. To eat, a philosopher requires both their left and right chopsticks.
Philosopher 0
( P0 )
chopstick 4 / \ chopstick 0
/ \
( P4 ) ( P1 )
| |
chopstick 3 chopstick 1
\ /
chopstick 2 \ /
( P3 ) -- ( P2 )Deadlock Risk:
If all 5 philosophers get hungry simultaneously and pick up their left chopstick at the exact same instant, every chopstick is held and each philosopher waits indefinitely for their right chopstick. A circular wait deadlock occurs.
Deadlock-Free Solutions:
- Asymmetric Philosopher Protocol: Odd-numbered philosophers pick up their Left chopstick first, then Right. Even-numbered philosophers pick up their Right chopstick first, then Left. This breaks circular wait symmetry.
- Limit Room Capacity: Allow at most 4 philosophers to sit at the table simultaneously using a counting semaphore initialized to 4.
- Monitor / State Solution: Allow a philosopher to pick up chopsticks only if both neighbors are not eating (
state[LEFT] != EATING && state[RIGHT] != EATING).
2. The Readers-Writers Problem
A shared database or file is accessed concurrently by multiple reader processes (which only read) and writer processes (which update data).
- Multiple readers can read simultaneously.
- Only one writer can write at a time (exclusive lock).
- No reader can read while a writer is writing.
Reader-Preference Solution & The Starvation Dilemma:
// READER PROCESS
wait(mutex);
read_count++;
if (read_count == 1)
wait(rw_mutex); // First reader locks out writers
signal(mutex);
// READING OCCURS HERE
wait(mutex);
read_count--;
if (read_count == 0)
signal(rw_mutex); // Last reader unlocks writers
signal(mutex);- Starvation Problem: In the Reader-Preference model, as long as at least one reader is active, subsequent readers can enter. A steady stream of incoming readers causes writer starvation indefinitely.
- Fair / Writer-Preference Solution: Introduce a queueing semaphore
queuethat preserves FIFO order. When a writer arrives, it holdsqueue, preventing newly arriving readers from jumping ahead until the writer has finished.
Important Exam Points & Quick Revision
Examiner Insights & University Exam Strategy:
- Definite Banker's Algorithm Question: A 10–15 mark numerical on Banker's Algorithm is guaranteed in the exam. Always show Need matrix calculation, state Work vector progression clearly, write the complete Safe Sequence, and verify the resource-request condition.
- Peterson's Algorithm: Frequently asked as a 5-mark question; write the complete C structure and prove all three criteria (Mutual Exclusion, Progress, Bounded Waiting).
- Dining Philosophers / Readers-Writers: Illustrate with clear diagrams and show how asymmetric access or counting semaphores eliminate deadlocks.
100% left on this page — finishing it closes the gap for Process Synchronization, Concurrency & Deadlocks.
Process Synchronization, Concurrency & Deadlocks still counts as a weak topic until you finish this note and answer its questions.
Practise this unitTest Your Understanding
Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.