flag[0]Falseturn0count0CRITICAL SECTIONflag[1]False1flag[0] = True2turn = 13while flag[1] and turn == 1:4 pass5count += 16flag[0] = False1flag[1] = True2turn = 03while flag[0] and turn == 0:4 pass5count += 16flag[1] = FalseT0T1
Back: shared memory (flag[0], turn, count, flag[1])Front: thread 0 and thread 1, each running Peterson's algorithmDiscs: the threads; pills: each read and write of shared memoryShared memory at the back: flag[0], turn, count and flag[1]. The critical section in the middle, where at most one thread may stand. Two threads in front, each with Peterson's six lines. Without protection both threads read 0 and write 1. With Peterson's algorithm thread 1, which wrote turn last, spins at line 3 while thread 0 is inside; then it takes its turn and count ends at 2. Modern CPUs and compilers reorder memory accesses for speed, so Peterson's algorithm written with plain loads and stores is not guaranteed to work on today's hardware. Real locks use atomic instructions and memory barriers instead; that is the next lesson.

The problem

  1. Two threads run at the same time and share memory. Each runs count += 1 once, so count should end at 2. But that one line is three steps for the CPU: read count, add 1, write it back.

Peterson's algorithm

One at a time

What happens

;; step 1/12 · shared
count += 1 on x86 (OSTEP ch. 26):
  mov  count, %eax     read
  add  $1, %eax        add 1
  mov  %eax, count     write back

each thread has its own registers;
count lives in memory both threads share

The figure treats each read or write of a shared value as happening all at once and in program order (sequential consistency). Peterson's algorithm is correct under that assumption, which is what the Python checker models. Modern CPUs and compilers reorder memory accesses for speed, so Peterson's algorithm written with plain loads and stores is not guaranteed to work on today's hardware. Real locks use atomic instructions and memory barriers instead; that is the next lesson.