The following program consists of 3 concurrent processes and 3 binary semaphores. The semaphores are initialized as S0 = 1, S1 = 0 and S2 = 0. Process P0: while (true) { wait(S0); print 'V'; release(S1); release(S2); } Process P1: wait(S1); wait(S0); print 'V'; Process P2: wait(S2); release(S0); How many times will process P0 print 'V'? A. At least twice B. Exactly twice C. Exactly thrice D. Exactly once

GATE 2010 · Operating System · Process Synchronization · medium

Answer: P0 prints 'V' exactly twice. Answer: B.

  1. First iteration of P0: P0 executes wait(S0): S0 goes 1->0. P0 prints 'V' (1st time). P0 does release(S1): S1 goes 0->1. P0 does release(S2): S2 goes 0->1. State: S0=0, S1=1, S2=1.
  2. P1 and P2 proceed; P0's second chance: P1: wait(S1) succeeds (S1: 1->0). P1: wait(S0) — S0=0, so P1 BLOCKS. P2: wait(S2) succeeds (S2: 1->0). P2: release(S0) — S0 goes 0->1. Now S0=1, P0 can loop: wait(S0) succeeds (S0: 1->0). P0 prints 'V' (2nd time). P0 does release(S1): S1 goes 0->1. P0 does release(S2): S2 goes 0->1. P1 was waiting on S0 and now S0=0, so now P1 gets S0 (S0: the release gave it to P0 first, but now P0 releases S1/S2 and loops back to wait(S0) finding S0=0 again). P1 wakes: S0 goes 0->0, P1 prints 'V'. P0 returns to while loop, waits on S0 — S0=0, blocks. P2 has already terminated. No one will release S0 again.
  3. Verify P0 cannot print a third time: After P0's second iteration: release(S1) wakes P1 which was blocked on wait(S0). But P0 already consumed S0 for its second iteration, and now P1 holds S0. P2 is done (single-run process). Nobody releases S0 for P0 a third time. P0 blocks indefinitely at wait(S0).