Lock-free data structures
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
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.
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اقرأ الدرس خطوة بخطوة
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 missesA 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 lockCompare-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()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 unchangedBoth 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 yetA 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 -> 5B'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 lostB 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 shortB 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]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 nodesThe 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)
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01What does compare-and-swap (CAS) on top do?
The compare and the write happen together, so no other thread can slip in between. On a mismatch nothing is written, which is what keeps the stack safe.
02Threads A and B both read top = 5. A's CAS(top, 5, 8) succeeds. What happens to B's CAS(top, 5, 9)?
B expected 5 but top holds 8, so the CAS reports failure and changes nothing. B loops, reads 8, links node 9 to node 8 and tries again.
03Why is the push loop called lock-free?
Apart from rare spurious failures of the weak form, a failed CAS means top changed, which means another thread completed a push. Some operation always finishes, even if a thread is paused mid-push. That is lock-free; every thread finishing in bounded steps would be the stronger wait-free.
04What is the ABA problem?
CAS compares only the value, not its history. With pops and reused nodes the value can look unchanged while the list behind it has changed. A change counter stored beside the pointer, or delayed freeing such as Linux RCU, guards against it.
05In the C program, why can push use atomic_compare_exchange_weak in its loop?
The weak form may fail even when the values match, but the loop just retries. On any failure C11 writes the current value of top into old, so the next attempt links to the right node. These functions are in <stdatomic.h>, new in C11.
المسرد
- Lock-free
- A guarantee for a shared data structure: whatever the timing, some thread always completes its operation in a finite number of steps. No thread ever waits for another to release a lock.
- Wait-free
- A stronger guarantee: every thread completes its own operation in a bounded number of steps, however the others behave.
- Compare-and-swap (CAS)
- An atomic instruction: if a memory word still holds an expected value, replace it with a new value; otherwise change nothing. It reports which happened. x86 calls it compare-and-exchange (cmpxchg).
- Atomic
- Done as one indivisible step: no other thread can see or act on a half-finished state.
- Linked stack
- A stack made of nodes, each pointing to the next, with one shared word (top) pointing to the first node.
- Starvation
- One thread never gets its own work done while others keep finishing. In a lock-free loop an unlucky thread can keep losing the race; only wait-free code rules that out.
- ABA problem
- A CAS that succeeds when it should not, because the value went from node X to Y and back to X between a thread's read and its CAS.
- RCU (read-copy-update)
- A Linux kernel technique for read-mostly data: readers take no lock, and old versions are freed only after every reader that could see them has finished.
الملاحظات والمصادر
- The card is Python-style pseudocode: cas(top, old, node) stands for the hardware instruction. Python itself has no compare-and-swap you can use from ordinary code; the C program in the details is the real thing.
- The worked example is OSTEP's lock-free list insert (chapter 32): do { n->next = head; } while (CompareAndSwap(&head, n->next, n) == 0). Berkeley CS162 shows the same loop for adding to a queue.
- Michael and Scott call this guarantee non-blocking; most texts today say lock-free. Wait-free is stronger: every thread, not just some thread, finishes in a bounded number of steps.
- In C11, atomic_compare_exchange_weak may fail even when the values match (a spurious failure); inside a retry loop that is harmless, and it can be faster on some CPUs.
- Push alone is safe as shown. Pop is where ABA bites, because a popped node can be freed and its memory reused while another thread still holds a pointer to it. Real lock-free stacks add a counter or a safe memory reclamation scheme.
- Lock-free code is hard to get right: OSTEP notes that a full lock-free list with insert, delete and lookup is non-trivial. Use a tested library or kernel primitive rather than writing your own.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 32: Common Concurrency Problems (lock-free insert)
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 28: Locks (compare-and-swap)
- Berkeley CS162, Lecture 8: Lock Implementation, Atomic Instructions (compare&swap for lock-free queues)
- MIT 6.1810 (2024), lecture notes: RCU
- M. Michael and M. Scott, Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms (PODC 1996)
- Linux kernel documentation: atomic_t wrappers (cmpxchg, try_cmpxchg)
- Linux kernel documentation: What is RCU?
- cppreference: atomic_compare_exchange_strong, atomic_compare_exchange_weak (C11)
- Linux man-pages: pthread_create(3)
اختبار يتاح بعد الخطوة الأخيرة.