Sub topic 7
Peterson's algorithm for two processes
This chapter assumes you know what a race condition is, what a critical section is, and the three requirements for a solution: mutual exclusion, progress and bounded waiting. It also assumes you can read C-like pseudocode and that you know a scheduler can preempt a process between any two instructions.
The problem Peterson solves
Two processes, numbered 0 and 1, share some data. Each has a critical section (CS), the code that touches that data. We want a purely software entry protocol and exit protocol with no special hardware instruction.
Two simpler attempts fail, and Peterson's algorithm combines their good parts.
- Strict alternation with a
turnvariable. A process enters only whenturnequals its number. This gives mutual exclusion, but it violates progress. If process 1 is slow or stays in its remainder section, process 0 cannot enter twice in a row, even though the CS is free. - Flags only. Each process sets
flag[i] = 1and waits while the other flag is set. Mutual exclusion holds, but if both set their flags at the same time, both wait forever. That is deadlock, and it also violates progress.
Peterson uses flags to say "I want in" and turn to break ties.
The algorithm
int flag[2] = {0, 0};
int turn = 0;
void enter_region(int i) {
int j = 1 - i;
flag[i] = 1;
turn = j;
while (flag[j] && turn == j)
;
}
void leave_region(int i) {
flag[i] = 0;
}Process i uses it like this:
enter_region(i);
/* critical section */
leave_region(i);
/* remainder section */Read the entry code in three steps:
flag[i] = 1announces that processiwants to enter.turn = jpolitely gives the other process priority. The last process to writeturnis the one that yields.- The
whileloop spins only if the other process also wants in (flag[j]) and it is the other's turn (turn == j).
The process waits only when both conditions hold. If the other process is not interested, flag[j] is 0 and the loop exits at once.
Why mutual exclusion holds
Suppose both processes are in the CS at the same time. Process 0 passed its loop test, so either flag[1] == 0 or turn == 1 held at that moment. The same is true for process 1 with the roles swapped.
Each process set its own flag to 1 before it wrote turn, and it does not clear the flag until it leaves. So when both are in the CS, both flags are 1. Then process 0 got through only because turn == 1, and process 1 got through only because turn == 0. turn cannot be both values at the same time.
More precisely, both processes executed turn = ... before entering. Whichever write came last decides the final value of turn. Say process 0 wrote last, so turn == 1. Then process 1 sees flag[0] == 1 && turn == 0 is false and may enter. Process 0 sees flag[1] == 1 && turn == 1 is true and must wait. Only one gets in.
Tracing the interleavings
The table shows the worst case: both processes try at almost the same time.
| Step | Process 0 | Process 1 | flag[0] | flag[1] | turn |
|---|---|---|---|---|---|
| 1 | `flag[0] = 1` | 1 | 0 | 0 | |
| 2 | `flag[1] = 1` | 1 | 1 | 0 | |
| 3 | `turn = 1` | 1 | 1 | 1 | |
| 4 | tests `flag[1] && turn == 1`: true, spins | 1 | 1 | 1 | |
| 5 | `turn = 0` | 1 | 1 | 0 | |
| 6 | tests `flag[0] && turn == 0`: true, spins | 1 | 1 | 0 | |
| 7 | tests `flag[1] && turn == 1`: false, enters CS | 1 | 1 | 0 |
At step 5, process 1 overwrites turn with 0. That releases process 0, which was waiting on turn == 1. Process 1 gave way last, so process 1 waits and process 0 goes first. When process 0 leaves and sets flag[0] = 0, process 1's test becomes false and it enters.
Progress and bounded waiting
Progress. If process 1 is in its remainder section, flag[1] == 0. Process 0's loop condition is then false, so process 0 enters without waiting. A process outside its CS never blocks another. The deadlock of the flags-only attempt cannot happen, because turn has exactly one value and so the loop condition is false for at least one of the two processes.
Bounded waiting. Suppose process 0 is waiting and process 1 leaves the CS. Process 1 may try to re-enter at once. It sets flag[1] = 1 and then turn = 0. That write hands priority to process 0, so process 1 now waits and process 0 enters. Process 0 therefore waits for at most one entry by process 1. The bound is 1.
Common errors
Other mistakes that GATE questions use:
- Setting
turn = iinstead ofturn = j. The process then yields to itself and the algorithm fails. - Using
||in place of&&. A process would wait whenever the other is merely interested, or whenever it is the other's turn. That brings back the progress failure of strict alternation. - Not clearing the flag on exit. The other process would wait forever.
- Extending to three processes without changes. The two-process version relies on
turnhaving two values. Generalisations exist (the filter algorithm), but this code does not scale.
Busy waiting and modern hardware
The loop while (flag[j] && turn == j); is busy waiting: the process keeps using CPU cycles while it waits. A lock that waits this way is a spinlock. That is acceptable for very short critical sections but wasteful otherwise.
The textbook proof assumes sequential consistency: every read and write happens in program order and is visible to the other CPU at once. Real CPUs and compilers break this. A store buffer can delay flag[i] = 1 so that the other CPU reads the old value, and a compiler may reorder the writes or hoist reads of flag[j] out of the loop. On such machines, Peterson's algorithm needs memory barriers (fences) between the writes and the loop, and the variables need to be volatile or atomic. In practice, systems use atomic hardware instructions or library locks instead, which the next chapters cover.
Properties at a glance
| Property | Peterson's algorithm |
|---|---|
| Mutual exclusion | Yes |
| Progress | Yes |
| Bounded waiting | Yes, bound of 1 |
| Number of processes | Two |
| Waiting style | Busy waiting |
| Special hardware needed | None, but needs sequentially consistent memory or fences |
Exercise
In Peterson's algorithm, process 0 executes flag[0] = 1; turn = 1; and is then preempted. Process 1 runs flag[1] = 1; turn = 0; and tests its loop. Which process can enter the critical section next, and why?
Show answer
Process 0 enters. After process 1's write the state is flag = {1, 1} and turn = 0. Process 1's test, flag[0] && turn == 0, is true, so process 1 spins. When process 0 resumes, its test, flag[1] && turn == 1, is false because turn is 0, so it enters. The process that wrote turn last is the one that waits.
Exercise
A student rewrites the entry code as turn = j; flag[i] = 1; while (flag[j] && turn == j);. Give an interleaving in which both processes are in the critical section.
Show answer
Process 0 runs turn = 1 and is preempted. Process 1 runs turn = 0, then flag[1] = 1. Its test sees flag[0] == 0, so it enters the CS. Process 0 resumes, runs flag[0] = 1, and tests: flag[1] == 1 but turn == 0, so the loop condition is false and it enters too. Both are in the CS, so mutual exclusion fails.