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 |
|
|
|
Enter critical section, perform actions, then exit critical section |
|
Perform other non-critical section actions |
Until false; |
For the program to guarantee mutual exclusion, the predicate P in the while loop should be:
- A.
flag[j] = trueandturn = i - B.
flag[j] = trueandturn = j - C.
flag[i] = trueandturn = j - D.
flag[i] = trueandturn = 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.
Process
isetsflag[i] = trueto declare that it wants the critical section.It then executes
turn = j, ceding priority to processj.To be safe,
imay proceed only whilejis NOT simultaneously demanding entry onj's own turn. So it must spin exactly whileflag[j] = trueandturn = jare both true; the moment either fails (jis not interested, orjhas handed the turn back),ienters.
Why the peer's variables, not its own.
If the predicate tested
flag[i]— a flagijust set to true — the flag part is always satisfied, so the wait collapses to a test onturnalone, breaking the symmetry the algorithm relies on.If the predicate tested
turn = i, then right afteriexecutedturn = jthe test is immediately false, soiwould 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.