Operating Systems
Process Synchronization
Shared data plus interleaved execution creates race conditions. Learn the three critical-section requirements, the classic software and hardware locks, and then trace semaphores until producer-consumer, readers-writers and dining philosophers feel routine.
GATE CSE process synchronization — race conditions, critical-section requirements, Peterson, Test-and-Set, semaphores, producer-consumer, readers-writers, dining philosophers and monitors, with semaphore traces, samples, flashcards and drills.
Learning outcomes
- State mutual exclusion, progress and bounded waiting and test a given lock against them
- Write and trace Peterson’s algorithm, Test-and-Set and swapped-order semaphore code
- Compute semaphore values and the number of blocked processes after a sequence of wait/signal operations
- Solve producer-consumer, readers-writers and dining-philosophers and explain how monitors differ from semaphores
Critical-section problem and lock solutions
- A RACE CONDITION occurs when the result depends on the order in which cooperating processes access shared data. A CRITICAL SECTION (CS) is a code segment that accesses shared data; the entry section, CS, exit section and remainder section form the structure of every process.
- A correct solution must satisfy: (1) MUTUAL EXCLUSION — at most one process in its CS; (2) PROGRESS — if no process is in the CS and some want to enter, only those not in their remainder section take part in choosing, and the choice cannot be postponed forever; (3) BOUNDED WAITING — after a process requests entry, only a bounded number of other processes can enter before it. No assumption is made about relative speeds.
- LOCK VARIABLE (lock = 0/1 with a separate test and set) fails mutual exclusion because testing and setting are not atomic. STRICT ALTERNATION (turn variable) guarantees mutual exclusion but violates PROGRESS: a process outside its CS can block the other by not taking its turn.
- PETERSON’S ALGORITHM for two processes i and j uses flag[2] and turn: entry: flag[i] = true; turn = j; while (flag[j] && turn == j) ; exit: flag[i] = false. It satisfies mutual exclusion, progress and bounded waiting (software, busy waiting) and assumes loads and stores are atomic and not reordered.
- TEST-AND-SET (TSL) is an atomic hardware instruction: boolean TestAndSet(boolean *target) { r = *target; *target = true; return r; } with lock initially false: while (TestAndSet(&lock)) ; CS; lock = false. It gives mutual exclusion and progress but NOT bounded waiting for more than two processes (a fast process can re-enter repeatedly). SWAP/compare-and-swap are similar.
- Spinlocks (busy waiting) waste CPU cycles but avoid a context switch; they are good on multiprocessors for very short critical sections. Disabling interrupts works only on a uniprocessor and is a kernel technique.
- Priority inversion: a high-priority process waits for a lock held by a low-priority one that is preempted by a medium-priority process. Priority inheritance temporarily raises the lock holder’s priority.
- Peterson’s with n processes needs more machinery (the bakery algorithm gives bounded waiting for n processes).
- The classic RACE: count++ is compiled to LOAD r, count; ADD r, 1; STORE count, r. If a producer’s count++ and a consumer’s count-- interleave their three instructions, the final count can be wrong (for example one update is lost). Any read-modify-write on shared data needs a critical section.
- Kernel-level solutions: DISABLE INTERRUPTS (uniprocessor only, never for long), hardware atomic instructions (Test-and-Set, Swap / Exchange, Compare-and-Swap, Fetch-and-Add) and MUTEX LOCKS built on them. A SPINLOCK busy-waits; a blocking mutex puts the waiter to sleep, which costs two context switches, so spinning is better when the critical section is shorter than a context switch.
- A solution that uses only a shared flag per process and no turn variable can DEADLOCK: both set their flags and each waits forever for the other (no progress). A solution that uses only a turn variable is strict alternation.
- Remember the order in which GATE tests properties: first mutual exclusion (can both be inside?), then progress (can the CS stay empty while someone wants it?), then bounded waiting (can one process be overtaken forever?).
| Solution | Mutual exclusion | Progress | Bounded waiting |
|---|---|---|---|
| Lock variable (non-atomic) | No | — | — |
| Strict alternation | Yes | No | Yes |
| Peterson (2 processes) | Yes | Yes | Yes |
| Test-and-Set spinlock | Yes | Yes | No |
| Semaphore with FIFO queue | Yes | Yes | Yes |
Worked example
Problem. Two processes each execute x = x + 1 (read, add, write, not atomic) N times on a shared x initially 0. What are the minimum and maximum final values?
Solution. Maximum is 2N when increments never overlap. The minimum is 2 (for N ≥ 2): process A reads 0, B performs N-1 increments, A writes 1, B reads 1, A performs its remaining increments to N, B writes 2 — this lost-update interleaving is the textbook worst case.
Peterson’s algorithm and software-lock traces
- Shared data: boolean flag[2] (initially false) and int turn. Entry for Pi (j = 1 - i): flag[i] = true; turn = j; while (flag[j] && turn == j) ; Exit: flag[i] = false. A process enters when the other is not interested (flag[j] false) OR it is this process’s turn (turn == i).
- WHY IT WORKS: if both are in the critical section, flag[0] = flag[1] = true and each passed its test, so turn == 0 and turn == 1 would both have to hold, impossible because turn holds a single value written last by one of them. Mutual exclusion follows. Progress and bounded waiting follow because a waiting process enters after at most one turn of the other.
- ORDER MATTERS: if Pi executes turn = j BEFORE flag[i] = true, both processes can slip in. Trace: Pi sets turn = j; Pj sets turn = i, then flag[j] = true, sees flag[i] false and enters; Pi then sets flag[i] = true, sees turn == i (not j) and also enters. Mutual exclusion is violated.
- Without turn (flags only) both can set their flags and wait for each other forever: deadlock, so progress fails. Without flags (turn only) the processes must strictly alternate, so progress fails. Test-and-Set with a single lock variable gives mutual exclusion and progress but, for n > 2 processes, not bounded waiting.
- Test-and-Set fix for bounded waiting: keep a waiting[n] array; on exit scan from i + 1 round-robin for the next waiting process and hand the lock to it directly instead of releasing the lock.
- Peterson’s algorithm is correct only if reads and writes of flag and turn are atomic and are not reordered by the compiler or CPU; on modern hardware memory barriers are needed.
| Variant of entry code | Mutual exclusion | Progress | Bounded waiting |
|---|---|---|---|
| flag[i]=true; turn=j; while(flag[j] && turn==j) | Yes | Yes | Yes |
| turn=j; flag[i]=true; ... (swapped lines) | No | — | — |
| flag only: flag[i]=true; while(flag[j]) | Yes | No (deadlock) | No |
| turn only: while(turn != i) | Yes | No (alternation) | Yes |
Worked example
Problem. Pi and Pj run Peterson’s entry code at nearly the same time. Pi: flag[i]=true; turn=j. Pj: flag[j]=true; turn=i. Pi tests, then Pj tests. Who enters first and who spins?
Solution. The last write to turn is Pj’s turn = i, so turn == i. Pi evaluates flag[j] && turn == j = true && false = false, so Pi ENTERS. Pj evaluates flag[i] && turn == i = true && true = true, so Pj SPINS until Pi sets flag[i] = false on exit. The writer of turn last always waits.
Semaphores and classic problems
- A SEMAPHORE is an integer S accessed only through two atomic operations: wait(S) / P(S): while (S <= 0) ; S-- and signal(S) / V(S): S++. In the blocking implementation wait decrements S and, if S < 0, blocks the caller in a queue; signal increments S and, if S ≤ 0, wakes one waiting process. Then a negative value means (-S) waiting processes.
- COUNTING semaphore: value over an unrestricted domain, initialised to the number of available resource units. BINARY semaphore (mutex-style) takes only 0 or 1; initialise to 1 for mutual exclusion. A semaphore initialised to 0 is used for ordering (signalling an event).
- Net value rule: S = initial - (completed waits) + (signals). If initial = 10, 6 wait operations and 4 signal operations complete, S = 10 - 6 + 4 = 8. If more waits than resources are issued, the extra processes block.
- MUTUAL EXCLUSION: semaphore mutex = 1; wait(mutex); CS; signal(mutex). Swapping to signal(mutex) ... wait(mutex) or doing wait twice breaks mutual exclusion or deadlocks.
- PRODUCER-CONSUMER (bounded buffer of N slots): semaphore empty = N, full = 0, mutex = 1. Producer: wait(empty); wait(mutex); put item; signal(mutex); signal(full). Consumer: wait(full); wait(mutex); get item; signal(mutex); signal(empty). If the producer does wait(mutex) BEFORE wait(empty) and the buffer is full, it holds mutex while blocked and the consumer cannot enter: DEADLOCK.
- READERS-WRITERS (first problem): many readers may read together, a writer needs exclusive access. Semaphores: mutex = 1 (protects readcount), wrt = 1, integer readcount = 0. The first reader does wait(wrt), the last reader does signal(wrt). Readers are favoured, so WRITERS CAN STARVE; the second problem favours writers and readers can starve.
- DINING PHILOSOPHERS: five philosophers, five chopsticks (semaphores = 1). If each philosopher picks up the left chopstick and then the right, all may hold their left one: DEADLOCK. Remedies: allow at most 4 philosophers at the table, pick up both chopsticks only if both are available (inside a critical section), or use an asymmetric order (odd picks left first, even picks right first). Starvation must still be considered.
- Semaphores with a FIFO queue give bounded waiting. Because semaphores are scattered through the program, mistakes (swapped order, missing signal) cause deadlocks or violate mutual exclusion — this motivates monitors.
- Counting semaphore initialised to K allows up to K processes inside the protected region at once; initialised to 1 it is a mutex; initialised to 0 it orders two actions (the waiter proceeds only after someone signals). With S = 2 guarding two printers and 5 processes each calling wait(S) once, 2 proceed, 3 block and S = -3.
- Wake-up order: with a plain (unspecified-order) queue a process may starve. A strong semaphore wakes waiters in FIFO order, so bounded waiting holds; a weak semaphore gives no such guarantee.
- Sleeping-barber pattern: customers = 0, barbers = 0, mutex = 1 and an integer waiting; a customer who finds all chairs taken leaves, otherwise does signal(customers) then wait(barbers). It tests the same ordering discipline as producer-consumer.
- Atomicity requirement: wait() and signal() themselves must execute atomically; on a uniprocessor this is done by disabling interrupts for the few instructions inside them, on a multiprocessor by spinlocks, so semaphores still busy-wait for a very short time.
Formulas to remember
-
S(final) = S(initial) - (number of wait operations) + (number of signal operations) -
Bounded buffer: empty = N, full = 0, mutex = 1
Worked example
Problem. Semaphores S = 1, T = 0. P: while(1) { wait(S); print A; signal(T); } Q: while(1) { wait(T); print B; signal(S); } What is printed?
Solution. P can print A first (S = 1). It signals T, allowing Q to print B and signal S, which allows P again. The output is strictly alternating ABABAB... because each process can run only after the other has signalled.
Monitors and condition variables
- A MONITOR is a high-level construct: shared data plus the procedures that operate on it, with the guarantee that only ONE process can be active inside the monitor at a time (mutual exclusion is automatic and enforced by the compiler/language).
- Condition variables x provide x.wait() and x.signal(). x.wait() suspends the caller and releases the monitor; x.signal() resumes exactly one suspended process (if none is waiting it has NO effect — unlike a semaphore signal, which is remembered by incrementing the counter).
- Signal semantics: HOARE (signal-and-wait: the signalling process waits, the awakened one runs immediately) versus MESA (signal-and-continue: the signaller continues, and the awakened process must recheck its condition in a while loop).
- Monitor-based dining philosophers use states THINKING, HUNGRY, EATING and a test() function so that a philosopher eats only if neither neighbour is eating; this is deadlock-free but can still starve a philosopher.
- Semaphores can implement monitors and vice versa. Java synchronized/wait/notify and POSIX mutex/condition variables are practical forms.
- Deadlock-prone patterns: acquiring two locks in opposite order in two threads; forgetting to release the lock on an exit path; waiting on a condition while holding another lock.
- Compare: semaphore signal is persistent (counter), condition signal is lost if nobody waits; semaphores are low-level, monitors are structured.
| Feature | Semaphore | Monitor condition variable |
|---|---|---|
| signal with no waiter | increments the counter (remembered) | lost (no effect) |
| Mutual exclusion | programmer must add wait/signal | automatic, one active process |
| Level | low-level primitive | high-level language construct |
| Typical error | wrong order or forgotten signal | missing while-recheck under Mesa semantics |
Worked example
Problem. Three processes P1, P2, P3 each execute wait(S) once on a semaphore S initialised to 1, with no signals. How many are blocked and what is S?
Solution. P1 decrements S to 0 and enters; P2 makes S = -1 and blocks; P3 makes S = -2 and blocks. So 2 processes are blocked and, in the negative-count implementation, S = -2 (|S| = number of waiting processes).
Semaphore traces and classic-problem checklist
- ORDERING with semaphores: to force P1’s statement A before P2’s statement B before P3’s statement C, use two semaphores initialised to 0. P1: A; signal(s1). P2: wait(s1); B; signal(s2). P3: wait(s2); C. The output is always A B C regardless of scheduling.
- CYCLIC ORDERING: initialise one semaphore to 1 and the others to 0 and let each process signal the next one; the output repeats A B C A B C... For P1: wait(S1); A; signal(S2); P2: wait(S2); B; signal(S3); P3: wait(S3); C; signal(S1) with S1 = 1, S2 = S3 = 0.
- When asked for the MAXIMUM or MINIMUM number of times something is printed, look for the interleaving that lets a wait() succeed before the matching signal() has been consumed (counting semaphores accumulate signals).
- BOUNDED BUFFER counters: with N = 5, after 3 puts and 1 take, full = 2, empty = 3. In general full + empty = N once no operation is in progress, and the number of blocked producers is -empty when empty is negative.
- READERS-WRITERS (first problem): the first reader locks writers out with wait(wrt), the last reader unlocks them with signal(wrt); a writer needs wrt for the whole write. If readers keep arriving, a writer starves. The second problem gives writers priority and readers may starve.
- DINING PHILOSOPHERS: 5 philosophers, 5 chopstick semaphores initialised to 1. All picking left first gives deadlock. Fixes: at most 4 seated (extra semaphore = 4), pick both only together inside a critical section, or asymmetric pickup order (odd left-right, even right-left).
- Monitor vs semaphore on a lost signal: signal on a semaphore is remembered; signal on a condition variable with no waiter is lost, so condition waits are placed inside a while loop under Mesa semantics.
| Classic problem | Semaphores (initial values) | Risk |
|---|---|---|
| Producer-consumer (N slots) | empty = N, full = 0, mutex = 1 | deadlock if mutex is taken before empty/full |
| Readers-writers (readers first) | mutex = 1, wrt = 1, readcount = 0 | writer starvation |
| Dining philosophers | chopstick[5] = 1 each | deadlock if all pick left first |
| Sleeping barber | customers = 0, barbers = 0, mutex = 1 | lost wake-ups if order is wrong |
| Ordering of two statements | sync = 0 | forgetting the signal blocks forever |
Worked example
Problem. S1 = 1, S2 = 0, S3 = 0. P1: while(1){ wait(S1); print "A"; signal(S2); } P2: while(1){ wait(S2); print "B"; signal(S3); } P3: while(1){ wait(S3); print "C"; signal(S1); } What is the output pattern and how many processes can be inside their print statement at once?
Solution. Only P1 can start (S1 = 1). It prints A and signals S2, which lets P2 print B and signal S3, which lets P3 print C and signal S1. The output is ABCABC... and at any instant exactly one of the three semaphores is 1 and the others are 0, so at most one process is between its wait and signal: strictly one at a time.
Exam tips
- Name the violated property: strict alternation fails PROGRESS; Test-and-Set fails BOUNDED WAITING; non-atomic lock variable fails MUTUAL EXCLUSION.
- Semaphore value = initial - waits + signals; if it goes below zero, |value| processes are blocked.
- In producer-consumer always wait(empty/full) BEFORE wait(mutex); reversing causes deadlock.
- First readers-writers can starve writers; dining philosophers with all-left-first can deadlock; at most N-1 philosophers or asymmetric order fixes it.
- A condition-variable signal with no waiting process is lost; a semaphore signal is not.
10 GATE-style MCQs for Process Synchronization with full explanations. Attempt each question before revealing the answer.
In a two-process solution using a shared variable turn (strict alternation) to enter the critical section, which requirement is violated?
Show answer & explanation
Answer: B
Mutual exclusion and bounded waiting hold, but a process in its remainder section that does not use its turn blocks the other process: progress is violated.
A spinlock implemented with an atomic Test-and-Set instruction for n > 2 processes satisfies:
Show answer & explanation
Answer: B
The atomic instruction gives mutual exclusion and progress, but the order in which waiting processes win is arbitrary, so bounded waiting is not guaranteed.
A counting semaphore is initialised to 10. Then 6 P (wait) operations and 4 V (signal) operations are completed on it. The resulting value is:
Show answer & explanation
Answer: B
10 - 6 + 4 = 8.
For a bounded-buffer producer-consumer problem with buffer size N, the correct initial values of the semaphores empty, full and mutex are:
Show answer & explanation
Answer: B
Initially all N slots are empty (empty = N), none is full (full = 0), and mutex = 1 allows one process into the buffer.
In the producer code the order of wait(mutex) and wait(empty) is interchanged. When the buffer is full the result is:
Show answer & explanation
Answer: B
The producer holds mutex while blocked on empty, so the consumer cannot get mutex to remove an item and signal empty: deadlock.
A binary semaphore S is initialised to 1. Three processes execute wait(S) once each with no signal in between. Under the blocking implementation with negative counts, the number of blocked processes and the value of S are:
Show answer & explanation
Answer: B
First process gets in (S = 0), the other two block (S = -1, -2).
Five philosophers each pick the left chopstick first and then the right one. To guarantee freedom from deadlock the maximum number of philosophers that may be allowed to sit at the table simultaneously is:
Show answer & explanation
Answer: C
With at most 4 philosophers seated, by pigeonhole at least one can pick up both chopsticks, so circular wait cannot be complete.
The mutual-exclusion code is signal(S); CS; wait(S); with S initialised to 1 (reversed order). What can happen?
Show answer & explanation
Answer: B
Each signal increases S, so no process is ever blocked and many can enter the CS together: mutual exclusion is violated.
In the first readers-writers solution (readers have priority), which problem can occur?
Show answer & explanation
Answer: B
As long as new readers keep arriving, readcount never drops to zero and the writer never gets wrt.
Which of the following statements about monitors is TRUE?
Show answer & explanation
Answer: C
Mutual exclusion within a monitor is automatic. A condition signal with no waiter has no effect, and monitors can be built from semaphores.
Extra page-specific practice beyond the GATE samples. Attempt all 8, then reveal answers to check your reasoning.
The minimum final value of x after two processes each execute x = x + 1 100 times concurrently (non-atomic, x starts at 0) is:
Show answer & explanation
Answer: A) 2
The adversarial interleaving with lost updates can reduce the value to 2. The maximum possible is 200.
A counting semaphore initialised to 3 is used to guard a resource with 3 identical units. The maximum number of processes that can be using the resource at the same time is:
Show answer & explanation
Answer: C) 3
Three waits succeed (S goes 3 → 0); the fourth blocks.
Two processes use semaphores S = 1 and T = 0. P: wait(S); print A; signal(T); Q: wait(T); print B; signal(S); both in infinite loops. The output sequence is:
Show answer & explanation
Answer: C) ABABAB...
Q cannot run until P signals T, and P cannot repeat until Q signals S, so A and B strictly alternate starting with A.
Busy waiting is acceptable for a lock mainly when:
Show answer & explanation
Answer: B) the critical section is very short on a multiprocessor
Spinning costs less than a context switch when the wait is brief and the lock holder runs on another CPU.
Which one of the following is NOT guaranteed by a Test-and-Set spinlock shared by 5 processes?
Show answer & explanation
Answer: C) bounded waiting
There is no ordering among spinning processes, so some process may be bypassed arbitrarily often.
In Peterson’s algorithm, if both processes set their flags to true at the same time, who enters the critical section first?
Show answer & explanation
Answer: C) the process that wrote turn first, because the other overwrote it later and so yields
turn holds the value written last; the process that wrote last gives priority to the other, so the one whose write came first proceeds.
For the dining-philosophers problem with semaphore chopsticks, using an asymmetric order (odd philosophers pick left first, even pick right first) gives:
Show answer & explanation
Answer: A) deadlock freedom
The asymmetry breaks the circular wait condition, so a deadlock cannot form.
When a signal() is executed on a condition variable inside a monitor and no process is waiting on it:
Show answer & explanation
Answer: B) the signal has no effect
Condition variables have no counter; the signal is simply lost.
Topic FAQs
What are the three requirements of a critical-section solution?
Mutual exclusion (only one process inside), progress (a decision on who enters cannot be postponed indefinitely and involves only competing processes) and bounded waiting (limit on how many others can enter after a request). GATE usually asks which one a given scheme violates.
Why does Test-and-Set not guarantee bounded waiting?
Any process that finds the lock free takes it, and nothing orders the waiting processes, so an unlucky process can lose the race repeatedly. A waiting-queue variant with a turn array restores bounded waiting.
What is the difference between a binary semaphore and a mutex?
Both enforce mutual exclusion. A mutex has an owner and only the locking thread should unlock it; a binary semaphore is a signalling mechanism that any process may signal. GATE questions usually treat a binary semaphore initialised to 1 as a mutex.
How do I decide the initial semaphore values?
Use 1 for mutual exclusion, N for resources with N identical units (such as empty slots), and 0 when a process must wait for an event or for another process to produce something first.
Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.