| 1 | title: A lock-free stack |
| 2 | part: Shared memory |
| 3 | summary: CAS on pointers, a push loop that never blocks, and the ABA problem that makes pop harder. |
| 4 | --- |
| 5 | `CAS` works on pointers as well as integers, and a pointer is how a bigger thing is swapped in atomically: build the new structure privately, then make it visible by changing one word. The classic example is a stack as a linked list whose head is that word. |
| 6 | |
| 7 | ## Push |
| 8 | |
| 9 | To push a node: point its `next` at the current head, then `CAS` the head from what you saw to the new node. If another thread pushed first, the `CAS` fails, because the head is no longer what you saw, so look again and retry. No thread ever waits for another, and none can stop the others by being slow. |
| 10 | |
| 11 | ```raz Treiber run |
| 12 | module Treiber; |
| 13 | import Out, Thread; |
| 14 | import SYSTEM; |
| 15 | |
| 16 | type Node = record next: ^Node; val: INT; end; |
| 17 | |
| 18 | const Threads = 4; Each = 5000; |
| 19 | |
| 20 | var |
| 21 | top: ^Node; (* the head, changed only by CAS *) |
| 22 | nodes: [Threads * Each]Node; (* every node a thread will push *) |
| 23 | |
| 24 | (* n onto the stack, without a lock *) |
| 25 | proc push(n: ^Node); |
| 26 | var old: ^Node; |
| 27 | begin |
| 28 | old := top; |
| 29 | n^.next := old; |
| 30 | while not CAS(top, old, n) do |
| 31 | old := top; (* lost the race: look again *) |
| 32 | n^.next := old; |
| 33 | end; |
| 34 | end; |
| 35 | |
| 36 | proc work(arg: ^U8); |
| 37 | var first, i: INT; |
| 38 | begin |
| 39 | first := INT(arg) * Each; |
| 40 | for i := 0 to Each - 1 do |
| 41 | nodes[first + i].val := first + i; |
| 42 | push(SYSTEM.ADR(nodes[first + i])); |
| 43 | end; |
| 44 | end; |
| 45 | |
| 46 | proc main*; |
| 47 | var th: [Threads]^Thread.Thread; i, count, sum: INT; err: ERROR; n: ^Node; |
| 48 | begin |
| 49 | for i := 0 to Threads - 1 do |
| 50 | th[i], err := Thread.spawn(work, ^U8(i)); |
| 51 | if err # nil then Out.str(MSG(err)); Out.ln; return; end; |
| 52 | end; |
| 53 | for i := 0 to Threads - 1 do Thread.join(th[i]); end; |
| 54 | n := top; |
| 55 | while n # nil do |
| 56 | INC(count); |
| 57 | sum := sum + n^.val; |
| 58 | n := n^.next; |
| 59 | end; |
| 60 | Out.int(count); Out.char(' '); Out.int(sum); Out.ln; |
| 61 | Out.int(Threads * Each * (Threads * Each - 1) div 2); Out.ln; |
| 62 | end; |
| 63 | |
| 64 | end Treiber. |
| 65 | ``` |
| 66 | |
| 67 | Twenty thousand nodes pushed by four threads at once; every one is on the stack exactly once, and the sum of their values is the sum of 0 to 19999. Nothing was lost, and there is no lock anywhere in the program. |
| 68 | |
| 69 | The loop in `push` is the shape of every lock-free algorithm: read, compute, `CAS`, and read again on failure. The `CAS` is sequentially consistent, so the node's `val` and `next`, written before it with ordinary stores, are visible to a thread that finds the node through `top`. |
| 70 | |
| 71 | ## Pop, and the ABA problem |
| 72 | |
| 73 | Pop takes the head off: read `top`, read its `next`, `CAS` the head from `top` to `next`. It looks as easy as push, and it isn't. Between the two reads and the `CAS`, other threads may pop that node, pop others, and push the same node back, now with a different `next`. The head is the same pointer again, so the `CAS` succeeds, and installs a `next` that is stale: nodes disappear, or the stack points into freed memory. This is the **ABA problem**: the word changed from A to B and back to A, and the `CAS` can't tell. |
| 74 | |
| 75 | There are three common ways out, and each has a cost: |
| 76 | |
| 77 | - **Never reuse a node while anyone might hold it.** Nodes from an arena that is reset only when all threads are done, as the nodes above come from a fixed array, can't come back as a different node. |
| 78 | - **Add a counter to the head**, so that A-B-A is A1-B2-A3. That is a word and a counter swapped together, and raz's `CAS` is for one word, so a program packs a small index and a counter into one `UINT`. |
| 79 | - **Don't pop concurrently.** Many threads push and one thread, at the end, takes everything with a single `XCHG(top, nil)` and walks the list in peace. A stack used this way for work lists and logs needs no more. |
| 80 | |
| 81 | ```raz Drain run |
| 82 | module Drain; |
| 83 | import Out, Thread; |
| 84 | import SYSTEM; |
| 85 | |
| 86 | type Node = record next: ^Node; val: INT; end; |
| 87 | |
| 88 | const Threads = 3; Each = 1000; |
| 89 | |
| 90 | var |
| 91 | top: ^Node; |
| 92 | nodes: [Threads * Each]Node; |
| 93 | |
| 94 | proc push(n: ^Node); |
| 95 | var old: ^Node; |
| 96 | begin |
| 97 | old := top; |
| 98 | n^.next := old; |
| 99 | while not CAS(top, old, n) do |
| 100 | old := top; |
| 101 | n^.next := old; |
| 102 | end; |
| 103 | end; |
| 104 | |
| 105 | proc work(arg: ^U8); |
| 106 | var first, i: INT; |
| 107 | begin |
| 108 | first := INT(arg) * Each; |
| 109 | for i := 0 to Each - 1 do |
| 110 | nodes[first + i].val := 1; |
| 111 | push(SYSTEM.ADR(nodes[first + i])); |
| 112 | end; |
| 113 | end; |
| 114 | |
| 115 | proc main*; |
| 116 | var th: [Threads]^Thread.Thread; i, count: INT; err: ERROR; all, n: ^Node; |
| 117 | begin |
| 118 | for i := 0 to Threads - 1 do |
| 119 | th[i], err := Thread.spawn(work, ^U8(i)); |
| 120 | if err # nil then Out.str(MSG(err)); Out.ln; return; end; |
| 121 | end; |
| 122 | for i := 0 to Threads - 1 do Thread.join(th[i]); end; |
| 123 | all := XCHG(top, nil); (* take the whole stack, atomically *) |
| 124 | n := all; |
| 125 | while n # nil do INC(count); n := n^.next; end; |
| 126 | Out.int(count); Out.str(" taken at once, "); |
| 127 | if top = nil then Out.str("none left\n"); end; |
| 128 | end; |
| 129 | |
| 130 | end Drain. |
| 131 | ``` |
| 132 | |
| 133 | The atomic exchange takes everything pushed so far in one step, so the walk that follows races with nobody. |
| 134 | |
| 135 | ## When to use it |
| 136 | |
| 137 | A lock-free structure is worth it when a lock would be held by a thread that can be descheduled, when the critical section is a single pointer, or when a signal handler or an interrupt must share data with the code it interrupts. Everywhere else a `Mutex` is shorter, easier to check, and fast enough. The advantage of knowing how to write the other kind is that you understand what the lock is doing for you. |