Short answer: Peterson’s algorithm gives two threads mutual exclusion with three shared variables: a flag for each thread and a single turn. A thread raises its flag, gives the turn to the other thread, and waits while the other flag is up and the turn still belongs to the other thread. The waiting condition is what makes the later arriver back off. The algorithm provides mutual exclusion and progress for two threads, and it assumes sequential consistency. On a machine that reorders stores, the flags need memory barriers or atomic operations.
What the problem actually asks
A lock built from ordinary loads and stores has to survive both threads arriving at once. Each thread announces interest and then defers to the other by writing the other’s id into turn. The thread that wrote turn last is the one that waits if both flags are up. Exactly one of them proceeds. The other sees either a lowered flag or a turn that has come back.
Two flags without a turn are not enough: both can see the other flag down before either raises its own, if the tests interleave. The turn variable breaks that tie. A single turn without flags cannot express “I am not interested,” so a thread that is not trying to enter would still own the turn and block the other forever.
What the algorithm guarantees
Under sequential consistency, at most one thread is in the critical section, a thread that is trying to enter and is alone will enter, and two threads that are both trying cannot deadlock. Bounded waiting holds for this two-thread algorithm: the waiting thread enters after the other releases. The algorithm does not work for three threads. The bakery algorithm is the n-thread lock from atomic reads and writes. Extra memory is three variables.
Modern compilers and CPUs reorder ordinary stores. A flag write can become visible after the turn write, or a spin can be cached forever. A correct implementation on real hardware uses atomic operations or explicit fences. The textbook interleaving proof does not mention those fences and is incomplete without them.
The working steps
- Shared state: flag[0] and flag[1], initially false, and turn.
- Thread i sets flag[i] = true, then sets turn = 1−i, then waits while flag[1−i] is true and turn is 1−i.
- The thread then enters the critical section.
- On exit it sets flag[i] = false. The other thread’s wait condition fails and it may enter.
- On hardware that reorders stores, place a memory barrier between the flag write, the turn write, and the spin, or use the language’s atomic type with the ordering the memory model requires.
Two threads and sequential consistency, or an explicit memory order, are the hypotheses. A third thread needs a different algorithm. A test-and-set lock is the practical mutual exclusion primitive and does not use this waiting pattern. Peterson’s algorithm is the two-thread lesson in why both a flag and a turn are required.
Approaches that look simpler and fail
| Approach | Why it fails when the turn write is omitted |
|---|---|
| Raise a flag and wait while the other flag is up, with no turn | Both threads can pass the test before either flag is visible as up, or both can wait forever after both flags are up. The turn picks a winner. |
| Use the algorithm for three threads by adding a flag | The two-thread waiting condition does not name a winner among three. The bakery algorithm is the n-thread construction. |
| Assume a store buffer preserves the textbook order | A reordered flag and turn break the interleaving proof. Fences or atomics restore the order the proof used. |
| Spin on a non-volatile flag that the compiler hoists | The compiler can load the flag once and loop forever. The flag has to be an atomic or an equivalent volatile access. |
An n-thread lock from reads and writes is Lamport’s bakery algorithm. A hardware test-and-set or compare-and-swap lock is the usual implementation. Peterson’s algorithm is the two-thread solution.
A working example
This Python fragment schedules every interleaving of two threads that run Peterson’s four steps. A state in which both threads are inside the critical section never appears. It prints exclusive.
# pc: 0 raise flag, 1 yield turn, 2 spin, 3 critical, 4 exit
def step(state, who):
flag, turn, pc = state
flag, pc = list(flag), list(pc)
other = 1 - who
if pc[who] == 0:
flag[who] = 1
pc[who] = 1
elif pc[who] == 1:
turn = other
pc[who] = 2
elif pc[who] == 2:
if flag[other] and turn == other:
pass
else:
pc[who] = 3
elif pc[who] == 3:
pc[who] = 4
elif pc[who] == 4:
flag[who] = 0
pc[who] = 5
return (tuple(flag), turn, tuple(pc))
start = ((0, 0), 0, (0, 0))
seen = {start}
stack = [start]
while stack:
state = stack.pop()
flag, turn, pc = state
if pc[0] == 3 and pc[1] == 3:
raise SystemExit("both inside")
for who in (0, 1):
if pc[who] <= 4:
nxt = step(state, who)
if nxt not in seen:
seen.add(nxt)
stack.append(nxt)
print("exclusive")
Where it is used
Peterson’s algorithm locks two threads with only reads and writes. It is a proof, not a library mutex. Two production threads use a futex or an atomic flag. Lamport’s bakery algorithm is the n-thread ticket proof in the same family.
When you can drop this algorithm
Drop a copy of the textbook spins into a language that reorders memory. Use atomics with a defined order, or a library mutex. Keep the algorithm as the mutual-exclusion proof for two threads once the memory order matches the proof.
Why this stays published
We publish this so a search for Peterson’s algorithm returns the flag-and-turn wait and the memory-order assumption it depends on. Peterson’s algorithm gives two threads mutual exclusion by raising a flag and yielding the turn, and it needs sequential consistency or explicit barriers to match the textbook proof.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
