The critical-section problem and Peterson's algorithm
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
When two threads share memory, a single line such as count += 1 can lose updates, because the CPU reads, adds and writes in separate steps. The code that touches shared data is a critical section, and any fix must keep threads out of it one at a time, without needless waiting and without starving anyone. Watch two threads run Peterson's algorithm, the classic two-flag, one-turn solution built from plain reads and writes, and see why it works and why real hardware still needs atomic instructions. The Software lesson on threads and concurrency shows the race and a simple lock; this lesson looks at the theory underneath. The Embedded course puts mutexes and semaphores to work on a microcontroller.
Two threads, one counter
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.
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
اقرأ الدرس خطوة بخطوة
Two threads, one counter
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.
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 shareA lost update
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.
thread 0 thread 1 count read 0 0 read 0 0 write 0 + 1 1 write 0 + 1 1 (should be 2) the same race in C99 with POSIX threads: #include <pthread.h> #include <stdio.h> #define N 1000000 static volatile long count = 0; /* shared by both threads */ static void *work(void *arg) { (void)arg; for (long i = 0; i < N; i++) count += 1; /* read, add, write: not atomic */ return NULL; } int main(void) { pthread_t a, b; pthread_create(&a, NULL, work, NULL); pthread_create(&b, NULL, work, NULL); pthread_join(a, NULL); pthread_join(b, NULL); printf("count = %ld (expected %ld)\n", count, 2L * N); return 0; } cc -std=c99 -pthread race.c && ./a.out often prints less than 2000000The critical-section problem
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.
the three requirements: mutual exclusion at most one thread in its critical section at a time progress if it is free and someone wants in, someone gets in, soon bounded waiting once a thread asks, the others can go first only a limited number of times we start again from count = 0Thread 0 raises its flag
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.
shared memory at the start: flag = [False, False] turn = 0 count = 0 thread 0, line 1: flag[0] = True flag = [True, False]Thread 0 offers the turn
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.
thread 0, line 2: turn = 1 flag = [True, False] turn = 1 turn is one shared value: only the last write staysThread 1 wants in too
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.
thread 1, line 1: flag[1] = True thread 1, line 2: turn = 0 (replaces the 1) flag = [True, True] turn = 0 both threads want in; turn = 0 says thread 0 goesThread 0 goes in
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 0, line 3: while flag[1] and turn == 1: flag[1] True turn == 1 False (turn is 0) True and False -> False: stop waiting thread 0 enters the critical sectionThread 1 spins
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.
thread 1, line 3: while flag[0] and turn == 0: flag[0] True turn == 0 True True and True -> True: keep waiting (pass) the CPU stays busy checking: spin-waitingOne thread inside
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, line 5: count += 1 read 0, write 1 count = 1 thread 1, line 3: still waiting flag[0] True and turn == 0 TrueThread 0 leaves
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 0, line 6: flag[0] = False flag = [False, True] turn = 0 count = 1 thread 1 checks again: flag[0] False -> False: stop waitingThread 1 gets its turn
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.
thread 1, line 3: flag[0] is False: go in thread 1, line 5: read 1, write 2 count = 2 thread 1, line 6: flag[1] = False end: flag = [False, False] turn = 0 count = 2Why it works
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.
mutual exclusion both wait only if turn == 0 and turn == 1: impossible, turn holds one value progress a thread waits only while the other wants in and has the turn bounded waiting after giving way once, a thread goes next every interleaving, checked in Python: # try every interleaving of two threads running Peterson's algorithm NEXT = {"flag": "turn", "turn": "wait", "wait": "read", "read": "write", "write": "unflag", "unflag": "done"} def step(s, me): # one atomic action of thread me pc, flag, turn, count, reg = list(s[0]), list(s[1]), s[2], s[3], list(s[4]) you, op = 1 - me, pc[me] if op == "done": return s if op == "flag": flag[me] = True elif op == "turn": turn = you elif op == "wait" and flag[you] and turn == you: return s # spin elif op == "read": reg[me] = count # count += 1 is a read ... elif op == "write": count = reg[me] + 1 # ... then a write elif op == "unflag": flag[me] = False pc[me] = NEXT[op] return (tuple(pc), tuple(flag), turn, count, tuple(reg)) start = (("flag", "flag"), (False, False), 0, 0, (0, 0)) seen, todo, both, finals = {start}, [start], 0, set() while todo: s = todo.pop() if all(p in ("read", "write") for p in s[0]): both += 1 if s[0] == ("done", "done"): finals.add(s[3]) for n in (step(s, 0), step(s, 1)): if n not in seen: seen.add(n); todo.append(n) print(len(seen), "states, both inside:", both, "final count:", sorted(finals)) prints: 42 states, both inside: 0 final count: [2]
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Two threads each run count += 1 once, starting from count = 0, with no protection. Which final values are possible?
count += 1 is a read, an add and a write. If both threads read 0 before either writes, both write 1 and one update is lost. If one finishes before the other reads, the result is 2. Checking every interleaving gives exactly 1 or 2.
02Which requirement says that, once a thread asks to enter, the other threads can only go ahead of it a limited number of times?
Bounded waiting rules out starvation. Mutual exclusion keeps at most one thread inside; progress says that if the critical section is free and someone wants in, the choice of who goes next cannot be put off forever.
03Both threads have set their flags to True. Thread 0 then sets turn = 1, and after that thread 1 sets turn = 0. Who enters first?
turn holds one value, the last one written: 0. Thread 1 waits while flag[0] is True and turn == 0, which is true. Thread 0 waits only while turn == 1, which is false, so thread 0 goes in. The thread that writes turn last gives way.
04Why can Peterson's algorithm never let both threads into the critical section together?
When both flags are up, thread 0 passes only if turn is 0 and thread 1 passes only if turn is 1. A single variable cannot hold both values, so one of them always waits.
05Why do real operating systems not use Peterson's algorithm as written?
The proof assumes each read and write happens in program order. Today's CPUs may perform memory operations in a different order for speed, which can break the algorithm. Hardware atomic instructions make real locks correct.
المسرد
- Thread
- One stream of instructions running inside a program. Threads of the same program share its memory.
- Race condition
- A bug where the result depends on the exact timing of threads, such as two threads both reading count before either writes it.
- Critical section
- A piece of code that uses shared data and must not be run by more than one thread at a time.
- Mutual exclusion
- The guarantee that at most one thread is inside its critical section at any moment.
- Progress
- If the critical section is free and some threads want in, one of them gets in; the decision is not put off forever.
- Bounded waiting
- Once a thread asks to enter, the other threads can go first only a limited number of times, so no thread starves.
- Spin-waiting
- Waiting by checking a condition in a loop, again and again, keeping the CPU busy. Also called busy waiting.
- Atomic
- Done all at once: other threads see it either not started or finished, never half done.
الملاحظات والمصادر
- 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.
- Peterson's algorithm (G. L. Peterson, 1981) is for exactly two threads. Versions for more threads exist, but operating systems use hardware-assisted locks.
- While thread 1 spins it keeps a CPU busy doing nothing useful. With one CPU it can only spin until the scheduler switches to thread 0; later lessons show locks that sleep instead.
- The C race program has a data race on purpose. The total it prints changes from run to run; on a multicore machine it is usually less than 2000000.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 26: Concurrency: An Introduction
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 28: Locks (aside on Dekker's and Peterson's algorithms)
- Berkeley CS162, Lecture 7: Concurrency, Mutual Exclusion, and Atomic Operations
- MIT 6.1810 (2024), lecture notes: Locking
- J. Bell, University of Illinois Chicago, Operating Systems course notes: Process Synchronization
- Linux kernel documentation: memory-barriers.txt
- Linux man-pages: pthread_create(3)
- Linux man-pages: pthread_join(3)
اختبار يتاح بعد الخطوة الأخيرة.