raz / site / public / advanced / atomics.html

207 lines · 15.0 KiB · raw · history · last change de634aad

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>Atomics - 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="Atomics - 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" aria-current="page">Atomics</a></li>
43<li><a href="ordering.html">Ordering and publication</a></li>
44<li><a href="lockfree.html">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 &middot; lesson 15 of 18</p><h1>Atomics</h1>
47<p>A volatile access is one access. An atomic is one *indivisible* step: nothing can happen between its read and its write, so two threads using it can't lose each other's work. There are three, built into the language as procedures, and they are sequentially consistent on every target:</p>
48<table><thead><tr><th>Call</th><th>Does</th></tr></thead><tbody><tr><td data-label="Call"><code>XADD(p, x)</code></td><td data-label="Does">adds <code>x</code> to <code>p</code> and returns the value before</td></tr><tr><td data-label="Call"><code>XCHG(p, x)</code></td><td data-label="Does">sets <code>p := x</code> and returns the value before</td></tr><tr><td data-label="Call"><code>CAS(p, old, new)</code></td><td data-label="Does">if <code>p = old</code>, sets <code>p := new</code> and returns <code>true</code>; otherwise <code>false</code></td></tr></tbody></table>
49<p><code>p</code> is a variable (or <code>q^</code> through a pointer <code>q</code>, even <code>^VOLATILE</code>) of type <code>INT</code>, <code>UINT</code> or a pointer type (<code>INT</code> or <code>UINT</code> for <code>XADD</code>); the atomic works on the variable itself, so no <code>ADR</code> is taken. A module that uses them says <code>import SYSTEM;</code>. They compile to single x86-64 instructions: <code>lock xadd</code>, <code>xchg</code> (which is always locked when it touches memory) and <code>lock cmpxchg</code>:</p>
50<div class="file"><span>Ops.raz</span></div><pre class="code"><code><span class="kw">module</span> Ops;
51<span class="kw">import</span> SYSTEM;
52
53<span class="kw">var</span> counter: <span class="ty">INT</span>;
54
55<span class="kw">proc</span> main*;
56<span class="kw">begin</span>
57 _ := <span class="ty">XADD</span>(counter, <span class="number">5</span>);
58 _ := <span class="ty">XCHG</span>(counter, <span class="number">100</span>);
59 _ := <span class="ty">CAS</span>(counter, <span class="number">100</span>, <span class="number">7</span>);
60<span class="kw">end</span>;
61
62<span class="kw">end</span> Ops.</code></pre>
63<pre class="output term"><code><span class="cmd">$ raz -S Ops.raz | grep -i &quot;lock\|xchg&quot;</span>
64 23 lock xadd [r8], rax
65 9 _ := XCHG(counter, 100);
66 43 xchg [r8], rax
67 67 lock cmpxchg [r8], r10</code></pre>
68<h2>What each one gives you</h2>
69<p><code>XADD</code> is a counter, or a ticket dispenser: every caller gets a different number. <code>XCHG</code> takes the old value and leaves a new one, which is a flag, a swap, or the release of a lock. <code>CAS</code> is the general one: "if nobody changed it since I looked, change it". Most lock-free code is a loop around it.</p>
70<div class="file"><span>Tickets.raz</span></div><pre class="code"><code><span class="kw">module</span> Tickets;
71<span class="kw">import</span> Out, Thread;
72<span class="kw">import</span> SYSTEM;
73
74<span class="kw">var</span>
75 next: <span class="ty">INT</span>; <span class="comment">(* the next ticket to give out *)</span>
76 seen: [<span class="number">4000</span>]<span class="ty">U8</span>; <span class="comment">(* which tickets were taken, one byte each *)</span>
77
78<span class="kw">proc</span> work(_arg: ^<span class="ty">U8</span>);
79<span class="kw">var</span> i, t: <span class="ty">INT</span>;
80<span class="kw">begin</span>
81 <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">1000</span> <span class="kw">do</span>
82 t := <span class="ty">XADD</span>(next, <span class="number">1</span>); <span class="comment">(* a ticket no other thread gets *)</span>
83 seen[t] := <span class="number">1</span>;
84 <span class="kw">end</span>;
85<span class="kw">end</span>;
86
87<span class="kw">proc</span> main*;
88<span class="kw">var</span> th: [<span class="number">4</span>]^Thread.Thread; i, taken: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>;
89<span class="kw">begin</span>
90 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span>
91 th[i], err := Thread.spawn(work, <span class="ty">nil</span>);
92 <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>;
93 <span class="kw">end</span>;
94 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>;
95 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3999</span> <span class="kw">do</span> taken := taken + seen[i]; <span class="kw">end</span>;
96 Out.int(next); Out.char(<span class="string">&#x27; &#x27;</span>); Out.int(taken); Out.ln;
97<span class="kw">end</span>;
98
99<span class="kw">end</span> Tickets.</code></pre>
100<pre class="output"><code>4000 4000
101</code></pre>
102<p>Four thousand tickets, four thousand different numbers, no two threads with the same one. Each thread writes into its own bytes of <code>seen</code>, so no plain write is shared.</p>
103<h2>A compare-and-swap loop</h2>
104<p>Anything that can be computed from the old value can be made atomic with a loop around <code>CAS</code>: read the value, compute the new one, and try to swap it in; if someone got there first, read again. Here is an atomic maximum, which no single instruction does.</p>
105<div class="file"><span>Peak.raz</span></div><pre class="code"><code><span class="kw">module</span> Peak;
106<span class="kw">import</span> Out, Thread;
107<span class="kw">import</span> SYSTEM;
108
109<span class="kw">var</span> peak: <span class="ty">INT</span>;
110
111<span class="comment">(* raises peak to v if v is bigger, however many threads call it *)</span>
112<span class="kw">proc</span> raise(v: <span class="ty">INT</span>);
113<span class="kw">var</span> seen: <span class="ty">INT</span>;
114<span class="kw">begin</span>
115 seen := peak;
116 <span class="kw">while</span> seen &lt; v <span class="kw">do</span>
117 <span class="kw">if</span> <span class="ty">CAS</span>(peak, seen, v) <span class="kw">then</span> <span class="kw">return</span>; <span class="kw">end</span>;
118 seen := peak; <span class="comment">(* someone changed it: look again *)</span>
119 <span class="kw">end</span>;
120<span class="kw">end</span>;
121
122<span class="kw">proc</span> work(arg: ^<span class="ty">U8</span>);
123<span class="kw">var</span> i, base: <span class="ty">INT</span>;
124<span class="kw">begin</span>
125 base := <span class="ty">INT</span>(arg);
126 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">999</span> <span class="kw">do</span> raise(base + i * <span class="number">7</span> <span class="kw">mod</span> <span class="number">1001</span>); <span class="kw">end</span>;
127<span class="kw">end</span>;
128
129<span class="kw">proc</span> main*;
130<span class="kw">var</span> th: [<span class="number">4</span>]^Thread.Thread; i: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>;
131<span class="kw">begin</span>
132 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span>
133 th[i], err := Thread.spawn(work, ^<span class="ty">U8</span>(i * <span class="number">1000</span>));
134 <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>;
135 <span class="kw">end</span>;
136 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>;
137 Out.int(peak); Out.ln;
138<span class="kw">end</span>;
139
140<span class="kw">end</span> Peak.</code></pre>
141<pre class="output"><code>3994
142</code></pre>
143<p>The result doesn't depend on how the threads interleave: it is the largest value any of them offered. That is the test of a correct atomic algorithm, and why this kind of code is written once, carefully, and used everywhere.</p>
144<h2>A lock, from first principles</h2>
145<p>A lock is a word that is 0 when free and 1 when held. To take it, <code>CAS</code> it from 0 to 1; if that fails, someone holds it, so try again. To give it up, <code>XCHG</code> it back to 0. This is exactly the library's <code>Lock</code>, printed from <code>lib/Lock.raz</code>:</p>
146<pre class="output term"><code><span class="cmd">$ sed -n &#x27;/^type Lock/,/^proc main/p&#x27; $RAZLIB/Lock.raz | head -n -2</span>
147type Lock* = record held: INT; end;
148
149(* Takes l, waiting while another thread holds it. *)
150proc take*(var l: Lock);
151var tries: INT;
152begin
153 tries := 0;
154 while not CAS(l.held, 0, 1) do
155 INC(tries);
156 if tries = 64 then Sys.yield; tries := 0; end;
157 end;
158end;
159
160(* Gives up l, which the caller holds. *)
161proc give*(var l: Lock);
162begin
163 _ := XCHG(l.held, 0);
164end;</code></pre>
165<p>And here is a use of it: a structure with two fields that must stay in step, which no single atomic can protect.</p>
166<div class="file"><span>Account.raz</span></div><pre class="code"><code><span class="kw">module</span> Account;
167<span class="kw">import</span> Out, Lock, Thread;
168
169<span class="kw">var</span>
170 lock: Lock.Lock;
171 deposits, balance: <span class="ty">INT</span>; <span class="comment">(* balance = 3 * deposits, always, under lock *)</span>
172
173<span class="kw">proc</span> work(_arg: ^<span class="ty">U8</span>);
174<span class="kw">var</span> i: <span class="ty">INT</span>;
175<span class="kw">begin</span>
176 <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">20000</span> <span class="kw">do</span>
177 Lock.take(lock);
178 <span class="ty">INC</span>(deposits);
179 <span class="ty">INC</span>(balance, <span class="number">3</span>);
180 Lock.give(lock);
181 <span class="kw">end</span>;
182<span class="kw">end</span>;
183
184<span class="kw">proc</span> main*;
185<span class="kw">var</span> th: [<span class="number">4</span>]^Thread.Thread; i: <span class="ty">INT</span>; err: <span class="ty">ERROR</span>;
186<span class="kw">begin</span>
187 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span>
188 th[i], err := Thread.spawn(work, <span class="ty">nil</span>);
189 <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>;
190 <span class="kw">end</span>;
191 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Thread.join(th[i]); <span class="kw">end</span>;
192 Out.int(deposits); Out.char(<span class="string">&#x27; &#x27;</span>); Out.int(balance); Out.ln;
193 <span class="kw">if</span> balance = <span class="number">3</span> * deposits <span class="kw">then</span> Out.str(<span class="string">&quot;in step\n&quot;</span>); <span class="kw">end</span>;
194<span class="kw">end</span>;
195
196<span class="kw">end</span> Account.</code></pre>
197<pre class="output"><code>80000 240000
198in step
199</code></pre>
200<p>A <code>Lock</code> spins, giving up the processor now and then, so it is for sections of a few instructions. <code>Thread.Mutex</code> sleeps on a futex, so it is for longer ones. A spinning lock held for a long time, or by a thread that was descheduled, burns processors; that is the price of its speed when contention is short.</p>
201<h2>Choosing</h2>
202<ul><li>A counter, a ticket, a flag: <code>XADD</code> or <code>XCHG</code>.</li><li>A value computed from the old one: a <code>CAS</code> loop.</li><li>Several variables that must change together: a <code>Lock</code> or a <code>Mutex</code>. Don't try to be clever with several atomics; the one invariant spanning them is the thing that breaks.</li></ul>
203<p>All three act on a word. For anything bigger, the thing you swap is a pointer to the bigger thing: the next lessons do exactly that.</p><p class="tryit">Save a program under its module&rsquo;s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="volatile.html">&larr; Volatile</a><a href="index.html">Contents</a><a class="next" href="ordering.html">Ordering and publication &rarr;</a></div></article></div>
204</main>
205<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer>
206</body>
207</html>