Peterson's solution
Animated two-process protocol.
Operating Systems: Peterson's Solution
1. Introduction & Assumptions
Peterson’s Solution is a classic software-based algorithm designed by Gary L. Peterson in 1981 to solve the critical-section problem for two processes (P0 and P1).
Hardware Assumption: It assumes that basic load and store machine instructions are atomic—meaning they complete in a single execution step without interruption.
2. Shared Variables and Process Algorithm
Peterson's algorithm relies on two shared data items between Process Pi and Process Pj (where j = 1 − i):
boolean flag[2];false. If flag[i] == true, process Pi wants to enter.int turn;turn == i, process Pi is granted permission to enter.// Algorithm for Process Pi (where j = 1 - i) do { flag[i] = true; turn = j; while (flag[j] && turn == j); /* Critical Section */ flag[i] = false; /* Remainder Section */ } while (true);
How the Entry Section Works:
- Express Intent: Pi sets
flag[i] = trueto declare it wants to enter its CS. - Polite Yield: Pi sets
turn = j, graciously offering process Pj the first chance to enter. - Busy Wait: Pi waits in the
whileloop as long as Pj wants to enter (flag[j] == true) AND it is Pj's turn (turn == j). - Exit Section: Once finished, Pi sets
flag[i] = false, freeing up the resource for Pj.
3. Proof of Correctness
Peterson’s Solution successfully meets all three requirements for a valid critical-section solution:
Each Pi enters CS only if flag[j] == false or turn == i. If both processes try to enter simultaneously, both set flag to true. However, turn can only hold one value (0 or 1) at a time. The process whose write to turn happened second will overwrite the first, forcing itself to wait and granting access to the other.
If Pj is in its remainder section, flag[j] == false. Thus, Pi can instantly bypass the while loop and enter its critical section without being blocked by Pj.
A process Pi will wait at most one entry cycle of Pj. As soon as Pj exits its CS, it sets flag[j] = false, immediately allowing Pi to enter. Even if Pj immediately re-enters its entry section, it sets turn = i, yielding to Pi.
4. Interactive Peterson's Algorithm Simulator
Use the controls below to step through Process 0 (P0) and Process 1 (P1) entering and exiting their critical sections. Observe how the shared flag array and turn variable prevent concurrent access.