ENع
→Locks and spinlocks
الدرس 19 · Synchronisation

Locks, spinlocks and atomic instructions

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

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

Two threads on two CPUs both add one to a shared counter. Without care, one update is lost. A lock fixes that, but how do you build a lock when the threads really run at the same moment? Plain loads and stores cannot do it: the check and the set must happen as one step. Follow a spinlock built on the hardware's test-and-set instruction as thread A takes the lock, thread B spins, A updates the counter and lets go, and B gets its turn. Then see why waiting by spinning wastes the CPU, and how a mutex sleeps in the kernel instead. The Software lesson on threads and concurrency shows the race itself; The critical-section problem and Peterson's algorithm sets out the rules a lock must follow.

ستتعلّم

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

شكل 19 · تفاعلي
01 / 11

Two threads, one counter

Two threads run on two CPUs and share one counter. counter++ is really three steps: load, add one, store. If the threads mix those steps, an update can be lost. A lock lets only one thread at a time into that code.

counter++   is three machine steps:
  load    read counter into a register
  add     register + 1
  store   write the register back

thread A runs on CPU 0, thread B on CPU 1, at the same time
critical section   the code that touches the shared counter
lock               lets one thread at a time into it
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Two threads, one counter

    Two threads run on two CPUs and share one counter. counter++ is really three steps: load, add one, store. If the threads mix those steps, an update can be lost. A lock lets only one thread at a time into that code.

    counter++   is three machine steps:
      load    read counter into a register
      add     register + 1
      store   write the register back
    
    thread A runs on CPU 0, thread B on CPU 1, at the same time
    critical section   the code that touches the shared counter
    lock               lets one thread at a time into it
  2. A plain flag fails

    First try: a flag. Wait while lock is 1, then set it to 1. But both threads can read 0 before either writes 1. Both think the lock is free, both enter, and counter ends at 1 instead of 2.

    the broken lock:   while (lock == 1) ;   lock = 1;
    
      A reads lock 0
      B reads lock 0
      A sets lock 1
      B sets lock 1
      counter 1
    
    check and set are two separate steps,
    so the other thread can slip in between them
    both inside: A and B   (no mutual exclusion)
  3. One indivisible step

    The fix comes from the hardware: an atomic instruction. Test-and-set writes 1 and returns the old value in one indivisible step: no other CPU can touch that memory word in between. On x86-64 this is xchg; C11 calls it atomic_exchange.

    test_and_set(&lock), as one step:
      old  = lock
      lock = 1
      return old
    
    x86-64    xchg (always locked when it touches memory)
    RISC-V    amoswap
    C11       atomic_exchange(&lock, 1)   <stdatomic.h>
    
    another atomic: compare-and-swap (x86: cmpxchg)
      if lock == expected: lock = new;  report the old value
    
    start again: lock = 0, counter = 0
  4. Thread A takes the lock

    Thread A runs test-and-set on lock. It swaps in a 1 and gets back 0. A 0 means the lock was free, so the loop ends and A owns the lock. lock now holds 1.

    line 1   while (test_and_set(&lock))
    
    A test_and_set -> 0
      swaps in 1, gets back 0: it was free
      while (0) ends the loop
    lock     = 1   (A owns it)
  5. Thread B spins

    Thread B runs test-and-set too. It swaps in a 1 and gets back 1: taken. So B loops and tries again, and again. This busy loop is a spinlock, and B's CPU stays busy doing no useful work.

    lines 1-2   while (test_and_set(&lock))   ;  // spin
    
    B test_and_set -> 1
    B test_and_set -> 1
      ...
      swaps 1 for 1: nothing changes, the answer says taken
    B is busy-waiting: running, but making no progress
  6. Only A is inside

    Holding the lock, A runs counter++: it loads 0, adds one and stores 1. B cannot get in while lock is 1, so nothing can slip between those three steps. This guarded code is the critical section.

    line 3   counter++;
    
    A   load  counter -> 0
    A   add   0 + 1   =  1
    A   store counter =  1
    B   still spinning: every test_and_set returns 1
  7. A unlocks

    A leaves the critical section and stores 0 in lock. One atomic store is enough to unlock, because only the thread that holds the lock ever does it.

    line 4   lock = 0;  // unlock
    
    lock = 0 on an atomic_int is an atomic store
    xv6:  __atomic_store_n(&lk->locked, 0, __ATOMIC_RELEASE)
    lock     = 0   (free)
  8. B gets its turn

    B's next test-and-set gets back 0, so now B owns the lock. It loads 1, adds one and stores 2, then unlocks. Two increments and counter is 2: nothing was lost.

    B test_and_set -> 0
    B counter 1 -> 2
    B unlock
    
    counter  = 2   lock = 0
    
    the whole program (C11 + POSIX threads):
    
    #include <pthread.h>
    #include <stdatomic.h>
    #include <stdio.h>
    
    static atomic_int lock = 0;   /* 0 = free, 1 = taken */
    static long counter = 0;
    
    static int test_and_set(atomic_int *l) {
        return atomic_exchange(l, 1);   /* write 1, return the old value */
    }
    
    static void *worker(void *arg) {
        (void)arg;
        for (int i = 0; i < 100000; i++) {
            while (test_and_set(&lock))
                ;  // spin
            counter++;
            lock = 0;  // unlock
        }
        return NULL;
    }
    
    int main(void) {
        pthread_t a, b;
        pthread_create(&a, NULL, worker, NULL);
        pthread_create(&b, NULL, worker, NULL);
        pthread_join(a, NULL);
        pthread_join(b, NULL);
        printf("counter = %ld\n", counter);
        return 0;
    }
    
    prints:
    counter = 200000
  9. The price of spinning

    Back to B waiting. Spinning burns CPU time. On a single CPU it is worse: A cannot even run to unlock until a timer interrupt switches threads. So spinlocks suit short critical sections on several CPUs, which is how kernels use them.

    replay: A holds the lock, B spins
    
    several CPUs   B spins while A works elsewhere:
                   fine if the critical section is short
    one CPU        B spins for its whole time slice;
                   A runs only after the scheduler switches
    
    kernels: hold spinlocks "for very short times" (MIT 6.1810)
  10. Sleep instead of spin

    A mutex waits by sleeping. On Linux, pthread_mutex_lock first tries an atomic instruction. If the lock is taken, a futex system call puts the thread to sleep in the kernel, and the unlock wakes it. No CPU time is burned.

    pthread_mutex_lock(&m)   (glibc on Linux)
      free?   one atomic instruction, no system call
      taken?  futex wait: sleep in the kernel's queue
              (only if the word still says taken)
    pthread_mutex_unlock(&m)
      waiters? futex wake: the kernel wakes one
    
    futex   a 32-bit word in user memory the kernel can wait on
  11. Locks in one picture

    Plain loads and stores cannot build a lock: the check and the set must be one atomic step. Test-and-set gives that step. Spin when the wait is short; sleep in the kernel when it may be long.

    the spinlock as a Python simulation:
    
    mem = {"lock": 0, "counter": 0}
    
    def test_and_set(name):     # one indivisible step
        old = mem[name]
        mem[name] = 1
        return old
    
    def thread(me):
        while test_and_set("lock") == 1:
            yield me + " spins"
        yield me + " has the lock"
        c = mem["counter"]       # load
        yield me + " loaded " + str(c)
        mem["counter"] = c + 1   # add one, store
        yield me + " stored " + str(c + 1)
        mem["lock"] = 0          # unlock
        yield me + " unlocked"
    
    running = [thread("A"), thread("B")]
    while running:              # take turns, one step each
        for t in list(running):
            try:
                print(next(t))
            except StopIteration:
                running.remove(t)
    print("counter =", mem["counter"])
    
    prints:
    A has the lock
    B spins
    A loaded 0
    B spins
    A stored 1
    B spins
    A unlocked
    B has the lock
    B loaded 1
    B stored 2
    B unlocked
    counter = 2

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