ENع
→Lock-free structures
الدرس S3 · Special topics

Lock-free data structures

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

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

A lock keeps shared data safe, but if the thread holding it is paused, everyone else waits. Lock-free data structures use no lock at all: each thread prepares its change privately and publishes it with one compare-and-swap. If another thread got there first, the swap fails, nothing breaks, and the thread simply tries again. Watch two threads push onto the same stack at once, one win, one retry, and no node lost. The lesson Locks, spinlocks and atomic instructions introduces compare-and-swap, and Concurrency bugs and event-based concurrency shows the deadlocks that lock-free code avoids.

ستتعلّم

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

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

Why go without a lock?

A lock lets one thread in at a time. If the thread holding it is paused, say its time slice ends or it hits a page fault, every other thread must wait. A lock-free structure never makes a thread wait for another.

with a lock      lock -> change -> unlock
                 holder paused  =>  everyone waits
lock-free        no lock at all
                 prepare privately, publish in ONE atomic step

delays that pause a lock holder (Michael & Scott 1996):
  scheduling preemption, page faults, cache misses
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Why go without a lock?

    A lock lets one thread in at a time. If the thread holding it is paused, say its time slice ends or it hits a page fault, every other thread must wait. A lock-free structure never makes a thread wait for another.

    with a lock      lock -> change -> unlock
                     holder paused  =>  everyone waits
    lock-free        no lock at all
                     prepare privately, publish in ONE atomic step
    
    delays that pause a lock holder (Michael & Scott 1996):
      scheduling preemption, page faults, cache misses
  2. A shared stack

    Our example is a stack of linked nodes. The shared word top says which node is first; each node points to the next. Now it holds node 5. To push, link the new node to the old top, then point top at it.

    top -> 5 -> null
    
    push(node), one thread alone:
      node.next = top     link to the current first node
      top = node          make it the new first node
    
    two threads doing both lines at once can lose a node:
    that is the race this lesson fixes without a lock
  3. Compare-and-swap

    The tool is compare-and-swap (CAS), one atomic instruction: if top still holds what I read, replace it with my node and report success; otherwise change nothing and report failure. No other thread can act in the middle.

    cas(top, expected, new):        one instruction, atomic
        if top == expected:
            top = new
            return True             success
        return False                failure: nothing changed
    
    x86      cmpxchg, "compare-and-exchange"
    C11      atomic_compare_exchange_weak / _strong
    Linux    cmpxchg(), try_cmpxchg()
  4. Both threads read top

    Thread A wants to push node 8 and thread B node 9, at the same moment. Both run line 2 and read top. Both see node 5 and keep it in their own variable old.

    line 2   old = top
    
    thread A   old = 5     (private: only A can see it)
    thread B   old = 5     (private: only B can see it)
    top        5           unchanged
  5. Both link their node

    Line 3: each thread points its new node at node 5. These nodes are still private, so nothing shared has changed yet. Any number of threads can do this at once.

    line 3   node.next = old
    
    thread A   node 8.next = 5
    thread B   node 9.next = 5
    top        5        no other thread can see 8 or 9 yet
  6. A swaps first

    Thread A runs cas(top, 5, 8). Top still holds 5, so in one atomic step top becomes 8: node 8 is now on the stack. The CAS reports success and A leaves the loop.

    line 4   cas(top, 5, 8)
             top == 5?  yes  ->  top = 8     True
    line 5   break: A is done
    
    stack    top -> 8 -> 5
  7. B's swap fails

    Thread B runs cas(top, 5, 9). But top now holds 8, not 5, so the CAS changes nothing and reports failure. A plain top = node here would have thrown node 8 away.

    line 4   cas(top, 5, 9)
             top == 5?  no, top is 8   ->  False
             nothing written
    
    without CAS: top = 9 and 9.next = 5
                 node 8 would be lost
  8. B tries again

    The loop sends B back to line 2. It reads top again and gets 8, then points node 9 at node 8. It lost nothing but a few instructions, and it never waited for A.

    loop     back to line 2
    line 2   old = top          old = 8
    line 3   node.next = old    node 9.next = 8
    
    C11: a failed atomic_compare_exchange writes the
    current top into old for you, so the retry is short
  9. B swaps and wins

    Now cas(top, 8, 9) finds 8 in top, so top becomes 9. The stack reads 9, 8, 5: both pushes kept, in some order, and no lock was ever taken.

    line 4   cas(top, 8, 9)   top == 8? yes -> True
    stack    top -> 9 -> 8 -> 5
    
    the run as a Python simulation:
    
    class Node:
        def __init__(self, value, nxt=None):
            self.value, self.next = value, nxt
    
    class Cell:                       # one shared memory word
        def __init__(self, value):
            self.value = value
    
    def cas(cell, expected, new):     # the hardware does this as ONE step
        if cell.value is expected:
            cell.value = new
            return True
        return False
    
    top = Cell(Node(5))
    a, b = Node(8), Node(9)
    old_a = top.value; a.next = old_a  # both threads read node 5
    old_b = top.value; b.next = old_b
    print("A:", cas(top, old_a, a))    # top was still 5
    print("B:", cas(top, old_b, b))    # top is 8 now
    old_b = top.value; b.next = old_b  # B tries again
    print("B:", cas(top, old_b, b))
    n, out = top.value, []
    while n:
        out.append(n.value)
        n = n.next
    print(out)
    
    prints:
    A: True
    B: False
    B: True
    [9, 8, 5]
  10. Someone always finishes

    B's CAS failed only because A's succeeded. A failed (strong) CAS always means another thread made progress, so the stack as a whole never stalls, even if a thread is paused mid-push. That guarantee is called lock-free.

    lock-free    some operation always completes in a
                 finite number of steps
    wait-free    stronger: EVERY thread completes in a
                 bounded number of steps
    
    a paused thread holds nothing, so no one waits for it
    but one unlucky thread can keep losing (starvation);
    only wait-free rules that out
    
    the real thing, C11 + POSIX threads (2 x 100000 pushes):
    
    #include <pthread.h>
    #include <stdatomic.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct node { int value; struct node *next; } node_t;
    static _Atomic(node_t *) top = NULL;
    
    static void push(int value) {
        node_t *n = malloc(sizeof *n);
        if (n == NULL) abort();
        n->value = value;
        node_t *old = atomic_load(&top);
        do {
            n->next = old;            /* link to the top we saw */
        } while (!atomic_compare_exchange_weak(&top, &old, n));
    }
    
    static void *worker(void *arg) {
        for (int i = 0; i < 100000; i++) push(*(int *)arg);
        return NULL;
    }
    
    int main(void) {
        int a = 8, b = 9;
        pthread_t ta, tb;
        pthread_create(&ta, NULL, worker, &a);
        pthread_create(&tb, NULL, worker, &b);
        pthread_join(ta, NULL);
        pthread_join(tb, NULL);
        long count = 0;
        for (node_t *n = atomic_load(&top); n != NULL; n = n->next) count++;
        printf("%ld nodes\n", count);
        return 0;
    }
    
    prints:
    200000 nodes
  11. The catch: ABA

    CAS checks only the value. If top goes from node X to Y and back to X between a read and a CAS, the CAS wrongly succeeds; with pops and reused nodes, that breaks the list. Fixes: a change counter beside top, or delayed freeing.

    ABA:   thread reads top = X
           others pop X, pop Y, push X again (same address)
           thread: cas(top, X, ...) succeeds, but X.next is stale
    
    fixes
      counter    top and a change count swapped together
                 (Michael & Scott: makes ABA "extremely unlikely")
      reclaim    never reuse a node a thread may still hold
                 (Linux RCU waits for readers before freeing)

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