Peterson's Solution
A software-only way for two processes to take turns in a critical section, using just two flags and one turn variable. It satisfies all three requirements of the critical-section problem, and it breaks on modern hardware without memory barriers.
The Critical Section Problem
- Critical section – code that accesses shared data and must not run in two processes at once.
- Entry section – the code a process runs to ask permission to enter.
- Exit section – the code it runs on leaving.
- Remainder section – everything else.
- Requirements – any solution must guarantee mutual exclusion, progress and bounded waiting.
When two processes update the same data — a counter, a bank balance, a linked list — without coordination, their instructions can interleave and produce a result neither intended. The critical-section problem asks for an entry and exit protocol that makes this impossible. Peterson's solution (Gary Peterson, 1981), also called Peterson's algorithm, is the classic software-only answer for two processes: no special instructions, just ordinary reads and writes of shared memory.
Any protocol is judged against three requirements, and an exam answer has to prove all three for this one.
- Mutual exclusion – at most one process is in its critical section at any moment
- Progress – if nobody is inside and someone wants in, someone gets in; a process in its remainder section has no say in who
- Bounded waiting – once a process asks to enter, the other can enter only a limited number of times before it
- Mutual exclusion alone is easy (never let anyone in); the other two rule out such cheats
Flag and Turn: The Entry and Exit Code
- Shared –
boolean flag[2] = {false, false}andint turn. - Entry (process i, other process j) –
flag[i] = true; turn = j; - Wait –
while (flag[j] && turn == j) ;— busy-wait. - Critical section – access the shared data.
- Exit –
flag[i] = false;
flag[i] means process i wants to enter. turn breaks ties: when both want in, it says whose turn it is to go first. The subtle step is that a process sets turn to the other process — it offers the other one priority.
If both processes arrive together, both raise their flags and both write turn. The two writes land one after the other, so turn ends up holding whichever was written last. That process has just handed the turn to the other one, so it waits while the other enters. A waiting process is released when the other clears its flag on exit, or when the other asks again and sets turn back to it.
Each variable is needed. Without turn, two processes that raise their flags together would each wait for the other forever: deadlock. Without the flags, the processes would be forced to strictly alternate, so one could not enter twice in a row even when the other never wants to, which breaks progress.
- Setting turn to yourself breaks it – P0 sets turn = 0 and enters while P1's flag is down; P1 then sets turn = 1, its test
turn == 0is false, and it walks in too - Swapping the first two lines breaks it – with
turn = jbeforeflag[i] = true, P0 writes turn = 1, P1 writes turn = 0, raises its flag and enters (P0's flag is still down), then P0 raises its flag, sees turn = 0 and enters as well - Order of the loop test does not matter –
turn == j && flag[j]reads the same two values
Proving the Three Requirements
- Mutual exclusion – for both to be inside, both flags must be true, so each passed its loop only because
turnpointed to itself;turncannot equal 0 and 1 at once. - Progress – a process in its remainder has
flag = false, so the other's loop condition is false and it enters immediately. - Bounded waiting – a process that requests entry sets
turnto the other; if it then waits, the other enters at most once beforeturncomes back.
The mutual-exclusion proof is by contradiction. Suppose P0 and P1 are both in their critical sections. Then flag[0] and flag[1] are both true. P0 got past while (flag[1] && turn == 1) so, with flag[1] true, turn must have been 0; P1 got past its loop so turn must have been 1. A single variable cannot hold both values at the time both tests were made, so the assumption is false. The figure below draws the same argument as two branches, one for each value of turn.
Bounded waiting has a bound of one: if P0 is waiting and P1 leaves and immediately asks again, P1's own entry code sets turn = 0, which releases P0 before P1 can enter a second time.
- Reads and writes are atomic – each one completes without being torn in half
- Memory is sequentially consistent – every process sees the writes in program order (the next section shows what happens when this fails)
- Nobody dies inside – a process that crashes in its critical section leaves its flag up, and the other waits forever
- Critical sections end – the bound of one entry counts entries, not time
Terms, operations, and practical uses
Terms to know
- Critical sectionCode that accesses shared data and must run in one process at a time.
- Busy waitingRepeatedly testing a condition in a loop instead of blocking.
- Memory barrierAn instruction that stops the CPU from reordering memory operations across it.
- Sequential consistencyAll processes see memory operations in one order that respects each program's order.
Related lessons
- Race conditions and critical sectionsWhy shared data needs protection.
- Mutexes, semaphores and monitorsThe OS tools used in practice.
- Producer–consumer problemA classic problem built on these guarantees.
- DeadlocksWhat the turn variable prevents.
- Bakery algorithmThe n-process version of the same idea.
Code in Python, C++ and Java
import sys
import threading
sys.setswitchinterval(1e-5) # switch threads often so the two really interleave
flag = [False, False]
turn = 0
counter = 0
ROUNDS = 20000
def worker(i):
global turn, counter
j = 1 - i
for _ in range(ROUNDS):
flag[i] = True # I want to enter
turn = j # but you may go first
while flag[j] and turn == j:
pass # busy-wait until the other is out or it is my turn
counter += 1 # critical section: read-modify-write on shared data
flag[i] = False # exit: no longer interested
threads = [threading.Thread(target=worker, args=(i,)) for i in (0, 1)]
for t in threads:
t.start()
for t in threads:
t.join()
print("counter =", counter, "expected", 2 * ROUNDS)#include <atomic>
#include <iostream>
#include <thread>
using namespace std;
// Sequentially consistent atomics stop the CPU and compiler from reordering
// the flag write past the read of the other flag, which breaks Peterson's.
atomic<bool> flag[2] = {false, false};
atomic<int> turn{0};
long long counter = 0;
const int ROUNDS = 20000;
void worker(int i) {
int j = 1 - i;
for (int r = 0; r < ROUNDS; r++) {
flag[i] = true; // I want to enter
turn = j; // but you may go first
while (flag[j] && turn == j) {
// busy-wait until the other is out or it is my turn
}
counter++; // critical section: read-modify-write on shared data
flag[i] = false; // exit: no longer interested
}
}
int main() {
thread t0(worker, 0), t1(worker, 1);
t0.join();
t1.join();
cout << "counter = " << counter << " expected " << 2LL * ROUNDS << "\n";
return 0;
}import java.util.concurrent.atomic.AtomicIntegerArray;
public class Main {
// Volatile and atomic accesses are sequentially consistent in Java, which
// is exactly the ordering Peterson's solution relies on.
static final AtomicIntegerArray flag = new AtomicIntegerArray(2);
static volatile int turn = 0;
static long counter = 0;
static final int ROUNDS = 20_000;
static void worker(int i) {
int j = 1 - i;
for (int r = 0; r < ROUNDS; r++) {
flag.set(i, 1); // I want to enter
turn = j; // but you may go first
while (flag.get(j) == 1 && turn == j) {
Thread.onSpinWait(); // busy-wait until the other is out or it is my turn
}
counter++; // critical section: read-modify-write on shared data
flag.set(i, 0); // exit: no longer interested
}
}
public static void main(String[] args) throws InterruptedException {
Thread t0 = new Thread(() -> worker(0));
Thread t1 = new Thread(() -> worker(1));
t0.start();
t1.start();
t0.join();
t1.join();
System.out.println("counter = " + counter + " expected " + 2L * ROUNDS);
}
}Step through it
Running on P0 and P1 both request the critical section at the same time
Limitations: Busy Waiting and Modern CPUs
Peterson's solution busy-waits: a waiting process keeps executing its loop test, using CPU time that another process could use. On a single CPU this can be especially wasteful, because the process holding the critical section cannot make progress while the waiter spins. It also only handles two processes; generalisations such as the filter lock and Lamport's bakery algorithm cover n processes at higher cost.
More importantly, it is not guaranteed to work on modern hardware. Processors and compilers reorder independent memory operations for speed: a process's write to flag[i] can still be sitting in a store buffer when it reads flag[j]. If both processes do this, both read false and both enter. Peterson's solution assumes sequential consistency, which real CPUs do not provide by default.
It works again with memory barriers or sequentially consistent atomics — the C++ and Java code on this page use std::atomic and volatile/atomic variables for exactly that reason. In practice, operating systems use hardware instructions such as test-and-set and compare-and-swap to build mutex locks, and Peterson's solution is taught because it shows precisely what those locks must guarantee.
| Peterson's solution | Test-and-set / CAS lock | |
|---|---|---|
| Processes | Exactly 2 | Any number |
| Hardware support | None, if memory is sequentially consistent | Atomic instructions |
| Works on modern CPUs | Only with memory barriers | Yes |
| Waiting | Busy-wait | Busy-wait (spinlock) or block (mutex) |
| Bounded waiting | Yes, bound 1 | Not by plain test-and-set; needs extra logic |
- Two processes only: the Bakery Algorithm extends the idea to n
- On one CPU with strict priorities, a high-priority waiter can spin forever while the low-priority holder never runs
- Real systems use atomic instructions, mutexes and semaphores: see Test-and-Set and Spinlocks