| 1 | <!doctype html> |
| 2 | <html lang="en"> |
| 3 | <head> |
| 4 | <meta charset="utf-8"> |
| 5 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 6 | <title>A lock-free stack - More Raz</title> |
| 7 | <meta name="description" content="raz: a small systems language in Wirth's tradition, for x86-64 Linux."> |
| 8 | <meta name="theme-color" content="#E07A5F"> |
| 9 | <meta property="og:title" content="A lock-free stack - More Raz"> |
| 10 | <meta property="og:description" content="A small systems language for x86-64 Linux. No run time, no GC, one report."> |
| 11 | <meta property="og:image" content="https://raz.lucela.org/social.png"> |
| 12 | <meta name="twitter:card" content="summary_large_image"> |
| 13 | <link rel="icon" href="../favicon.svg" type="image/svg+xml"> |
| 14 | <link rel="icon" href="../favicon-32.png" type="image/png" sizes="32x32"> |
| 15 | <link rel="apple-touch-icon" href="../apple-touch-icon.png"> |
| 16 | <link rel="stylesheet" href="../style.css"> |
| 17 | </head> |
| 18 | <body> |
| 19 | <header><nav><a class="mark" href="../index.html"><img src="../logo.svg" width="26" height="26" alt="">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header> |
| 20 | <main> |
| 21 | <div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'> |
| 22 | <li><a href="fmt.html">Output and formatting</a></li> |
| 23 | <li><a href="bytes.html">Strings and bytes</a></li> |
| 24 | <li><a href="collections.html">Lists, arrays, maps and sorting</a></li> |
| 25 | <li><a href="files.html">Files and the command line</a></li> |
| 26 | <li><a href="processes.html">Time, randomness and other programs</a></li> |
| 27 | <li><a href="allocators.html">Writing an allocator</a></li> |
| 28 | </ol> |
| 29 | <h3>Standing alone</h3><ol start='7'> |
| 30 | <li><a href="static.html">A program with no run time</a></li> |
| 31 | <li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li> |
| 32 | <li><a href="lifecycle.html">Starting, ending, and signals</a></li> |
| 33 | <li><a href="targets.html">One module, one file per target</a></li> |
| 34 | </ol> |
| 35 | <h3>The machine</h3><ol start='11'> |
| 36 | <li><a href="asm.html">Procedures in assembly</a></li> |
| 37 | <li><a href="syscalls.html">System calls</a></li> |
| 38 | <li><a href="listing.html">What the compiler makes</a></li> |
| 39 | </ol> |
| 40 | <h3>Shared memory</h3><ol start='14'> |
| 41 | <li><a href="volatile.html">Volatile</a></li> |
| 42 | <li><a href="atomics.html">Atomics</a></li> |
| 43 | <li><a href="ordering.html">Ordering and publication</a></li> |
| 44 | <li><a href="lockfree.html" aria-current="page">A lock-free stack</a></li> |
| 45 | <li><a href="ring.html">A ring buffer between threads</a></li> |
| 46 | </ol></aside><article><p class="kicker">Shared memory · lesson 17 of 18</p><h1>A lock-free stack</h1> |
| 47 | <p><code>CAS</code> 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.</p> |
| 48 | <h2>Push</h2> |
| 49 | <p>To push a node: point its <code>next</code> at the current head, then <code>CAS</code> the head from what you saw to the new node. If another thread pushed first, the <code>CAS</code> 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.</p> |
| 50 | <div class="file"><span>Treiber.raz</span></div><pre class="code"><code><span class="kw">module</span> Treiber; |
| 51 | <span class="kw">import</span> Out, Thread; |
| 52 | <span class="kw">import</span> SYSTEM; |
| 53 | |
| 54 | <span class="kw">type</span> Node = <span class="kw">record</span> next: ^Node; val: <span class="ty">INT</span>; <span class="kw">end</span>; |
| 55 | |
| 56 | <span class="kw">const</span> Threads = <span class="number">4</span>; Each = <span class="number">5000</span>; |
| 57 | |
| 58 | <span class="kw">var</span> |
| 59 | top: ^Node; <span class="comment">(* the head, changed only by CAS *)</span> |
| 60 | nodes: [Threads * Each]Node; <span class="comment">(* every node a thread will push *)</span> |
| 61 | |
| 62 | <span class="comment">(* n onto the stack, without a lock *)</span> |
| 63 | <span class="kw">proc</span> push(n: ^Node); |
| 64 | <span class="kw">var</span> old: ^Node; |
| 65 | <span class="kw">begin</span> |
| 66 | old := top; |
| 67 | n^.next := old; |
| 68 | <span class="kw">while</span> <span class="kw">not</span> <span class="ty">CAS</span>(top, old, n) <span class="kw">do</span> |
| 69 | old := top; <span class="comment">(* lost the race: look again *)</span> |
| 70 | n^.next := old; |
| 71 | <span class="kw">end</span>; |
| 72 | <span class="kw">end</span>; |
| 73 | |
| 74 | <span class="kw">proc</span> work(arg: ^<span class="ty">U8</span>); |
| 75 | <span class="kw">var</span> first, i: <span class="ty">INT</span>; |
| 76 | <span class="kw">begin</span> |
| 77 | first := <span class="ty">INT</span>(arg) * Each; |
| 78 | <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Each - <span class="number">1</span> <span class="kw">do</span> |
| 79 | nodes[first + i].val := first + i; |
| 80 | push(SYSTEM.<span class="ty">ADR</span>(nodes[first + i])); |
| 81 | <span class="kw">end</span>; |
| 82 | <span class="kw">end</span>; |
| 83 | |
| 84 | <span class="kw">proc</span> main*; |
| 85 | <span class="kw">var</span> th: [Threads]^Thread.Thread; i, count, sum: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; n: ^Node; |
| 86 | <span class="kw">begin</span> |
| 87 | <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Threads - <span class="number">1</span> <span class="kw">do</span> |
| 88 | th[i], err := Thread.spawn(work, ^<span class="ty">U8</span>(i)); |
| 89 | <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; |
| 90 | <span class="kw">end</span>; |
| 91 | <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Threads - <span class="number">1</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>; |
| 92 | n := top; |
| 93 | <span class="kw">while</span> n # <span class="ty">nil</span> <span class="kw">do</span> |
| 94 | <span class="ty">INC</span>(count); |
| 95 | sum := sum + n^.val; |
| 96 | n := n^.next; |
| 97 | <span class="kw">end</span>; |
| 98 | Out.int(count); Out.char(<span class="string">' '</span>); Out.int(sum); Out.ln; |
| 99 | Out.int(Threads * Each * (Threads * Each - <span class="number">1</span>) <span class="kw">div</span> <span class="number">2</span>); Out.ln; |
| 100 | <span class="kw">end</span>; |
| 101 | |
| 102 | <span class="kw">end</span> Treiber.</code></pre> |
| 103 | <pre class="output"><code>20000 199990000 |
| 104 | 199990000 |
| 105 | </code></pre> |
| 106 | <p>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.</p> |
| 107 | <p>The loop in <code>push</code> is the shape of every lock-free algorithm: read, compute, <code>CAS</code>, and read again on failure. The <code>CAS</code> is sequentially consistent, so the node's <code>val</code> and <code>next</code>, written before it with ordinary stores, are visible to a thread that finds the node through <code>top</code>.</p> |
| 108 | <h2>Pop, and the ABA problem</h2> |
| 109 | <p>Pop takes the head off: read <code>top</code>, read its <code>next</code>, <code>CAS</code> the head from <code>top</code> to <code>next</code>. It looks as easy as push, and it isn't. Between the two reads and the <code>CAS</code>, other threads may pop that node, pop others, and push the same node back, now with a different <code>next</code>. The head is the same pointer again, so the <code>CAS</code> succeeds, and installs a <code>next</code> that is stale: nodes disappear, or the stack points into freed memory. This is the <strong>ABA problem</strong>: the word changed from A to B and back to A, and the <code>CAS</code> can't tell.</p> |
| 110 | <p>There are three common ways out, and each has a cost:</p> |
| 111 | <ul><li><strong>Never reuse a node while anyone might hold it.</strong> 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.</li><li><strong>Add a counter to the head</strong>, so that A-B-A is A1-B2-A3. That is a word and a counter swapped together, and raz's <code>CAS</code> is for one word, so a program packs a small index and a counter into one <code>UINT</code>.</li><li><strong>Don't pop concurrently.</strong> Many threads push and one thread, at the end, takes everything with a single <code>XCHG(top, nil)</code> and walks the list in peace. A stack used this way for work lists and logs needs no more.</li></ul> |
| 112 | <div class="file"><span>Drain.raz</span></div><pre class="code"><code><span class="kw">module</span> Drain; |
| 113 | <span class="kw">import</span> Out, Thread; |
| 114 | <span class="kw">import</span> SYSTEM; |
| 115 | |
| 116 | <span class="kw">type</span> Node = <span class="kw">record</span> next: ^Node; val: <span class="ty">INT</span>; <span class="kw">end</span>; |
| 117 | |
| 118 | <span class="kw">const</span> Threads = <span class="number">3</span>; Each = <span class="number">1000</span>; |
| 119 | |
| 120 | <span class="kw">var</span> |
| 121 | top: ^Node; |
| 122 | nodes: [Threads * Each]Node; |
| 123 | |
| 124 | <span class="kw">proc</span> push(n: ^Node); |
| 125 | <span class="kw">var</span> old: ^Node; |
| 126 | <span class="kw">begin</span> |
| 127 | old := top; |
| 128 | n^.next := old; |
| 129 | <span class="kw">while</span> <span class="kw">not</span> <span class="ty">CAS</span>(top, old, n) <span class="kw">do</span> |
| 130 | old := top; |
| 131 | n^.next := old; |
| 132 | <span class="kw">end</span>; |
| 133 | <span class="kw">end</span>; |
| 134 | |
| 135 | <span class="kw">proc</span> work(arg: ^<span class="ty">U8</span>); |
| 136 | <span class="kw">var</span> first, i: <span class="ty">INT</span>; |
| 137 | <span class="kw">begin</span> |
| 138 | first := <span class="ty">INT</span>(arg) * Each; |
| 139 | <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Each - <span class="number">1</span> <span class="kw">do</span> |
| 140 | nodes[first + i].val := <span class="number">1</span>; |
| 141 | push(SYSTEM.<span class="ty">ADR</span>(nodes[first + i])); |
| 142 | <span class="kw">end</span>; |
| 143 | <span class="kw">end</span>; |
| 144 | |
| 145 | <span class="kw">proc</span> main*; |
| 146 | <span class="kw">var</span> th: [Threads]^Thread.Thread; i, count: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>; all, n: ^Node; |
| 147 | <span class="kw">begin</span> |
| 148 | <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Threads - <span class="number">1</span> <span class="kw">do</span> |
| 149 | th[i], err := Thread.spawn(work, ^<span class="ty">U8</span>(i)); |
| 150 | <span class="kw">if</span> err # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="ty">MSG</span>(err)); Out.ln; <span class="kw">return</span>; <span class="kw">end</span>; |
| 151 | <span class="kw">end</span>; |
| 152 | <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> Threads - <span class="number">1</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>; |
| 153 | all := <span class="ty">XCHG</span>(top, <span class="ty">nil</span>); <span class="comment">(* take the whole stack, atomically *)</span> |
| 154 | n := all; |
| 155 | <span class="kw">while</span> n # <span class="ty">nil</span> <span class="kw">do</span> <span class="ty">INC</span>(count); n := n^.next; <span class="kw">end</span>; |
| 156 | Out.int(count); Out.str(<span class="string">" taken at once, "</span>); |
| 157 | <span class="kw">if</span> top = <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="string">"none left\n"</span>); <span class="kw">end</span>; |
| 158 | <span class="kw">end</span>; |
| 159 | |
| 160 | <span class="kw">end</span> Drain.</code></pre> |
| 161 | <pre class="output"><code>3000 taken at once, none left |
| 162 | </code></pre> |
| 163 | <p>The atomic exchange takes everything pushed so far in one step, so the walk that follows races with nobody.</p> |
| 164 | <h2>When to use it</h2> |
| 165 | <p>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 <code>Mutex</code> 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.</p><p class="tryit">Save a program under its module’s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="ordering.html">← Ordering and publication</a><a href="index.html">Contents</a><a class="next" href="ring.html">A ring buffer between threads →</a></div></article></div> |
| 166 | </main> |
| 167 | <footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer> |
| 168 | </body> |
| 169 | </html> |