Lesson 2 · Synchronization and deadlocks

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.

Peterson's Solution concept diagramThe code of Peterson's solution for process i, divided into entry section, critical section, exit section and remainder, beside the three requirements it satisfies: mutual exclusion, progress and bounded waiting.do {flag[i] = true;(1)turn = j;(2)while (flag[j] && turn == j);(3)/* critical section */flag[i] = false;(4)/* remainder section */} while (true);entrycriticalexitremainderMutual exclusionturn holds one value, so (3) letsat most one process through at a timeProgressa process not interested has flag = false,so (3) never blocks the other oneBounded waiting(2) yields the turn, so the other processenters at most once before this oneexit (4) is a single write that releases the waiting process
1

The Critical Section Problem

  1. Critical section – code that accesses shared data and must not run in two processes at once.
  2. Entry section – the code a process runs to ask permission to enter.
  3. Exit section – the code it runs on leaving.
  4. Remainder section – everything else.
  5. 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
2

Flag and Turn: The Entry and Exit Code

  1. Shared – boolean flag[2] = {false, false} and int turn.
  2. Entry (process i, other process j) – flag[i] = true; turn = j;
  3. Wait – while (flag[j] && turn == j) ; — busy-wait.
  4. Critical section – access the shared data.
  5. 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 == 0 is false, and it walks in too
  • Swapping the first two lines breaks it – with turn = j before flag[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
3

Proving the Three Requirements

  1. Mutual exclusion – for both to be inside, both flags must be true, so each passed its loop only because turn pointed to itself; turn cannot equal 0 and 1 at once.
  2. Progress – a process in its remainder has flag = false, so the other's loop condition is false and it enters immediately.
  3. Bounded waiting – a process that requests entry sets turn to the other; if it then waits, the other enters at most once before turn comes 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.

flag[0] = flag[1] = trueboth want the critical sectionturn = 0P1's loop test is true → P1 waitsturn = 1P0's loop test is true → P0 waitsat most one process entersturn cannot be 0 and 1 at once
  • 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
Key reference

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.
Implementation

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);
    }
}
Watch it run

Step through it

Running on P0 and P1 both request the critical section at the same time

P0 (i = 0, j = 1)flag[0] = trueturn = 1while (flag[1] && turn == 1);critical sectionflag[0] = falseremainder sectionP1 (i = 1, j = 0)flag[1] = trueturn = 0while (flag[0] && turn == 0);critical sectionflag[1] = falseremainder sectionsharedflag[0]falseflag[1]falseturn0critical section: emptyflag = interest, turn = tie-breaker
Step 1

Two processes, three shared variables

flag[i] says "Pi wants to enter". turn says whose turn it is to go first when both want in. Both processes start in their remainder sections, so neither flag is set.

Output
1 / 15
4

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 compared with hardware-based locks
Peterson's solutionTest-and-set / CAS lock
ProcessesExactly 2Any number
Hardware supportNone, if memory is sequentially consistentAtomic instructions
Works on modern CPUsOnly with memory barriersYes
WaitingBusy-waitBusy-wait (spinlock) or block (mutex)
Bounded waitingYes, bound 1Not 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