ENع
→Critical sections
الدرس 18 · Synchronisation

The critical-section problem and Peterson's algorithm

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة12 خطوة5 أسئلةIntermediate
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 18 · تفاعلي
01 / 12

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
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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
  2. A 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 2000000
  3. The 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 = 0
  4. Thread 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]
  5. 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 stays
  6. Thread 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 goes
  7. Thread 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 section
  8. Thread 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-waiting
  9. One 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 True
  10. Thread 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 waiting
  11. Thread 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 = 2
  12. Why 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]

اختبار يتاح بعد الخطوة الأخيرة.