Consider Peterson's algorithm for mutual exclusion between two concurrent…

2001

Consider Peterson's algorithm for mutual exclusion between two concurrent processes i and j. The program executed by process $i$ is shown below.

Repeat

flag[i] = true;

turn = j;

while(P) do no-op;

Enter critical section, perform actions, then exit critical section

flag[i] = false;

Perform other non-critical section actions

Until false;

For the program to guarantee mutual exclusion, the predicate P in the while loop should be:

  1. A.

    flag[j] = true and turn = i

  2. B.

    flag[j] = true and turn = j

  3. C.

    flag[i] = true and turn = j

  4. D.

    flag[i] = true and turn = i

Attempted by 14 students.

Show answer & explanation

Correct answer: B

Concept.

Peterson's algorithm lets a process enter its critical section only when its peer is not also contending for it, or when the turn has been ceded to it. A process announces its intent by setting its own flag to true, then politely passes the turn to the other process. It must then busy-wait as long as BOTH of these hold at the same time: the OTHER process also wants to enter (its flag is true) AND it is still the OTHER process's turn. The wait must therefore test the peer's flag and the peer's turn — never the process's own variables.

Applying it to process i.

  1. Process i sets flag[i] = true to declare that it wants the critical section.

  2. It then executes turn = j, ceding priority to process j.

  3. To be safe, i may proceed only while j is NOT simultaneously demanding entry on j's own turn. So it must spin exactly while flag[j] = true and turn = j are both true; the moment either fails (j is not interested, or j has handed the turn back), i enters.

Why the peer's variables, not its own.

  • If the predicate tested flag[i] — a flag i just set to true — the flag part is always satisfied, so the wait collapses to a test on turn alone, breaking the symmetry the algorithm relies on.

  • If the predicate tested turn = i, then right after i executed turn = j the test is immediately false, so i would never wait — both processes could be inside the critical section together, destroying mutual exclusion.

Cross-check. Substitute flag[j] = true and turn = j: when j is also contending and holds the turn, i spins; as soon as j leaves (flag[j] = false) or yields (turn = i), i proceeds. By symmetry process j waits on flag[i] = true and turn = i. The two predicates can never both be false-to-enter at once, so exactly one process is admitted — mutual exclusion holds and there is no deadlock.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir