CS FundamentalsVery hardProduct company interview · GATE level

Two processes (i = 0, 1; j = 1 - i) share bool flag[2] = {false, false} and int turn, and each runs entry code, then its critical section, then flag[i] = false. Every individual read and write is atomic and sequentially consistent. Which entry code guarantees both mutual exclusion and freedom from deadlock? V1: turn = j; flag[i] = true; while (flag[j] && turn == j); V2: flag[i] = true; turn = i; while (flag[j] && turn == j); V3: flag[i] = true; turn = i; while (flag[j] && turn == i); V4: flag[i] = true; while (flag[j]);

  1. A. V1 and V4
  2. B. V1 only
  3. C. V2 and V3
  4. D. V3 only

Correct answer: D. V3 only

V3 is Peterson's algorithm with the roles of turn mirrored: whoever writes turn last is the one that waits, so both cannot pass the loop, and the earlier writer always gets through. V1 swaps the two writes: P0 sets turn = 1, P1 sets turn = 0 and flag[1], enters (flag[0] still false), then P0 sets flag[0] and sees turn == 0 != 1, entering too. V2 waits on the wrong value: P0 sets flag[0] and turn = 0 and enters while flag[1] is false; P1 then sets flag[1] and turn = 1, sees turn != 0 and walks in as well. V4 is safe but both can set their flags and then spin forever - a deadlock. All four were checked by exhaustively exploring every interleaving.

More Operating Systems questions

Exams that ask this topic