The Critical Section Problem & Semaphores
“Race conditions, Mutual Exclusion, Progress, Bounded Waiting, and Semaphore operations.”
1.The Race Condition & The Critical Section Problem
§ 4.1.When multiple processes share common storage (RAM, files, global variables) and access it concurrently, the final outcome depends on the exact execution order of interleaving instructions. This bug is a Race Condition.
To prevent race conditions, the code region that accesses shared resources is designated as the Critical Section (CS). A valid solution to the Critical Section problem MUST satisfy three mandatory criteria:
1. Mutual Exclusion (Safety): If process Pᵢ is executing in its critical section, no other processes can be executing in their critical sections.
2. Progress (Liveness): If no process is in its CS and some processes wish to enter, only processes not in their remainder sections can participate in deciding who enters next, and this selection cannot be postponed indefinitely.
3. Bounded Waiting (Fairness/Starvation-freedom): There must exist a bound on the number of times other processes are allowed to enter their critical sections after a process has requested entry, preventing starvation.
2.Peterson's Algorithm: Software Mutual Exclusion for Two Processes
§ 4.2.Can software alone guarantee mutual exclusion without special hardware instructions? In 1981, Gary L. Peterson devised a classic algorithmic solution for two processes, alternating between their critical and remainder sections.
Consider two processes, P_0 and P_1. Let the current process be P_i and the other process be P_j (where j = 1 - i). Peterson's algorithm shares two variables:
• boolean flag[2]; (where flag[i] = true indicates that process P_i is ready to enter its critical section).
• int turn; (indicates whose turn it is to enter the critical section).
The Algorithm Structure for Process P_i:
``c
flag[i] = true; // 1. Declare intent: I want to enter
turn = j; // 2. Be polite: Offer priority to the other process
while (flag[j] && turn == j); // 3. Busy-wait while other wants in AND has turn
/ CRITICAL SECTION /
flag[i] = false; // 4. Exit: Release claim
/ REMAINDER SECTION /
``
Proof of Correctness:
1. Mutual Exclusion Guaranteed: For both processes to be in the CS simultaneously, both flag[0] and flag[1] must be true, and turn 0 AND turn 1 must hold simultaneously. Since turn is a scalar variable that can only hold one value at a time, at least one process was blocked in the while loop.
2. Progress Guaranteed: If P_j is not in its CS and has no desire to enter (flag[j] == false), the while condition for P_i immediately evaluates to false, allowing P_i to enter without delay. If both try to enter concurrently, turn will be set to either 0 or 1 by whichever write executes last, permitting the other process to enter immediately.
3. Bounded Waiting Guaranteed: A process waits at most one critical section entry of the other process. Once P_j exits, it resets flag[j] = false, freeing P_i.
3.Semaphores: Dijkstra's Synchronization Primitive
§ 4.3.While Peterson's algorithm works for two processes, scaling software synchronization to N processes introduces significant complexity and CPU-burning busy-waiting. In 1965, Edsger Dijkstra introduced the Semaphore.
A semaphore S is an integer variable that, apart from initialization, is accessed only through two standard atomic hardware/kernel operations: wait() (P-operation) and signal() (V-operation).
Atomic Definition of wait(S):
``c
wait(S) {
S = S - 1;
if (S < 0) {
// add this process to semaphore's waiting queue
block();
}
}
``
Atomic Definition of signal(S):
``c
signal(S) {
S = S + 1;
if (S <= 0) {
// remove a process P from the waiting queue
wakeup(P);
}
}
``
Crucially, the modification to S and the test must execute atomically (uninterruptibly) — guaranteed by the OS kernel disabling interrupts on uniprocessors or using hardware spinlocks (test_and_set) on multiprocessors.
4. Interactive Semaphore Simulator
Simulate counting and binary semaphores live. Trigger wait(S) (P-operation) and signal(S) (V-operation) for processes P1, P2, and P3 to observe how S manages entry and queues blocked processes.
Semaphore State & Blocked Queue Simulator
Observe how wait(S) decrements S and blocks processes when S < 0, while signal(S) increments S and awakens blocked processes.
› Semaphore initialized to 1
5. Counting vs. Binary Semaphore
Dijkstra introduced two classes of semaphores for synchronization problems.
| Feature / Aspect | Binary Semaphore (Mutex) | Counting Semaphore |
|---|---|---|
| Value Range | Only 0 or 1. | Any integer value (-k to +N). |
| Primary Use Case | Mutual exclusion for a single exclusive resource (Critical Section). | Managing access to a finite pool of N identical resource units (e.g. buffer slots). |
| Negative Value Meaning | In standard definition, if < 0, represents number of blocked processes. | If S = -k, exactly k processes are currently waiting in the semaphore queue. |
✎ Takeaway: A binary semaphore enforces strict 1-at-a-time mutual exclusion; a counting semaphore manages pools of N resources.
6. GATE Lens & Verified PYQs
Syllabus focus, recurring numerical patterns, common traps, and clearly labelled exam practice. Questions remain source-pending until an official paper and answer key are attached.
Semaphore arithmetic (counting initial value, sequence of wait and signal operations, finding final value and queue length) is a recurring 2-mark GATE question.
- •Given initial semaphore value S = N, after p wait operations and q signal operations, what is the value of S and how many processes are blocked?
- •If final S ≥ 0, exactly 0 processes are blocked!
- •If final S < 0, exactly |S| processes are blocked in the waiting queue!
Exam Practice / Source Verification Required
1 problemA counting semaphore S is initialized to 7. Then, 20 P (wait) operations and 15 V (signal) operations are conducted on S in some arbitrary order. What is the final value of the semaphore S, and how many processes are blocked in the waiting queue?
7. 1-Minute Panic Revision
“Critical Section requires: Mutual Exclusion (at most 1 in CS), Progress (no deadlock by non-CS processes), Bounded Waiting (no starvation). Peterson's algorithm solves CS for 2 processes. Semaphores solve CS for N processes.”
- •Peterson: flag[i]=true; turn=j; while(flag[j] && turn==j); / CS / flag[i]=false;
- •wait(S) / P(S): S = S - 1; if (S < 0) block();
- •signal(S) / V(S): S = S + 1; if (S <= 0) wakeup(process);
- •If S < 0: exactly |S| processes are sleeping in the blocked queue. If S >= 0: 0 processes blocked.
- •Never confuse Mutual Exclusion with Progress (Progress prevents deadlock).
- •Peterson's algorithm satisfies all 3 criteria on sequential consistency, but needs memory fences on modern multicore hardware.
- •A binary semaphore initialized to 0 is used for signaling/synchronization (order enforcement), NOT mutual exclusion.
Primary Academic References & Exam Sources
Every concept in Notes From a B.Tech Brain is synthesized from authoritative academic texts, seminal peer-reviewed research, verified exam archives, and renowned university lectures.
Official slides on Peterson's solution, test-and-set hardware instructions, and counting semaphore implementations.
Free chapter PDF walking through semaphores as locks, semaphores for ordering, and reader-writer problems.
IIT Kharagpur lecture on race conditions, mutual exclusion conditions, and semaphore queuing.
If the textbook derivation did not click immediately, consult these targeted video lessons:
Crystal-clear numerical breakdown of semaphore values (positive vs negative), waiting queues, and atomic P/V operations.
Deep-dive into the exact definition of Progress and why strict alternation fails the progress condition.
Curated lectures on Critical Section Problem, Peterson's Algorithm, Semaphores & Classic Concurrency Problems:
First-principles clarity on why simple software flags fail without hardware test-and-set.
Visualizing semaphore value modifications and solving classic producer-consumer flows.
Rigorous academic proof and counter-examples of synchronization invariants.
Mathematical rigor and handling high-difficulty GATE synchronization questions.