The problem
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.
With no protection, both threads can read count while it is still 0. Each adds 1 and writes back 1. Two increments ran, yet count is 1. A result that depends on timing like this is a race condition.
Line 5 touches shared data, so it is a critical section. Entry code (lines 1 to 4) and exit code (line 6) must give three things: one thread inside at a time, no needless waiting, and every waiter gets a turn.
Peterson's algorithm
Peterson's algorithm uses two shared flags and one shared turn. Thread 0 runs line 1: flag[0] = True means "I want to enter". It does not go in yet.
Next, thread 0 sets turn = 1: "if we both want in, you go first". This politeness is the trick. Whoever writes turn last is the one who waits.
Before thread 0 checks, thread 1 runs its first two lines: flag[1] = True, then turn = 0. turn holds one value, so this write replaces thread 0's. Thread 1 wrote turn last, so thread 1 will wait.
One at a time
Thread 0 checks line 3: flag[1] is True, but turn is 0, not 1. The loop waits only while both parts are true, so it ends at once and thread 0 enters the critical section.
Thread 1 checks its line 3: flag[0] is True and turn is 0. Both are true, so it loops, running lines 3 and 4 again and again and re-reading the shared values. This busy loop is called spin-waiting.
Inside, thread 0 runs count += 1: it reads 0 and writes 1. Thread 1 cannot get in, so nothing can slip between the read and the write. Thread 1 keeps spinning.
Thread 0 leaves and runs its exit code, line 6: flag[0] = False, "I am done". On thread 1's next check, flag[0] is False, so its wait condition is no longer true.
Thread 1's loop ends and it goes in. It reads 1, writes 2, then leaves with flag[1] = False. Two increments, and count is 2: no update was lost. Thread 1 waited for only one turn of thread 0.
turn holds one value, so two waiting threads always let one through, and a thread that gives way waits at most one turn. A search of every interleaving never finds both inside. Real CPUs reorder memory accesses, so real locks use atomic instructions.
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.