raz / site / public / advanced / ordering.html

133 lines · 10.5 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>Ordering and publication - 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="Ordering and publication - 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" aria-current="page">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 16 of 18</p><h1>Ordering and publication</h1>
47<p>Atomics make one word safe. The harder question is about the *other* words: if one thread writes a value and then raises a flag, can another thread that sees the flag be sure it sees the value?</p>
48<p>The report is careful. Only volatile accesses, <code>CAS</code>, <code>XCHG</code>, <code>XADD</code> and <code>FENCE</code> are exact. Any other access is ordinary: an implementation may keep a variable in a register, leave out a write that nothing reads, and change the order of ordinary accesses, as long as each thread, on its own, does what the report says. A variable that one thread writes while another reads or writes it, unless both use volatile accesses or the atomic built-ins, or a <code>FENCE</code> orders them, holds no particular value then: a read of it gives a value it had or was given, or a mixture of their bytes. Nothing else of the program becomes undefined by it.</p>
49<p>In plain words: two threads that share an ordinary variable with no atomic, volatile or fence between them get no guarantee about what each sees.</p>
50<h2>The pattern that is guaranteed: publish through an atomic</h2>
51<p>The simplest correct way to hand a value to another thread: write it with ordinary stores, then store a flag with an atomic. The reader loops on the flag with an atomic read, and then reads the data. <code>XCHG</code> is the store; <code>XADD(p, 0)</code> is the load, which adds nothing and returns the value. Both are sequentially consistent, so everything written before the flag is visible after it is seen.</p>
52<div class="file"><span>Publish.raz</span></div><pre class="code"><code><span class="kw">module</span> Publish;
53<span class="kw">import</span> Out, Sys, Thread;
54<span class="kw">import</span> SYSTEM;
55
56<span class="kw">type</span> Message = <span class="kw">record</span> id: <span class="ty">INT</span>; text: [<span class="number">32</span>]<span class="ty">U8</span>; len: <span class="ty">INT</span>; <span class="kw">end</span>;
57
58<span class="kw">var</span>
59 msg: Message; <span class="comment">(* ordinary memory, written once, then published *)</span>
60 ready: <span class="ty">INT</span>; <span class="comment">(* the flag: only touched by atomics *)</span>
61
62<span class="kw">proc</span> producer(_arg: ^<span class="ty">U8</span>);
63<span class="kw">begin</span>
64 Sys.sleep(<span class="number">10</span>);
65 msg.id := <span class="number">7</span>;
66 msg.text := <span class="string">&quot;built before the flag&quot;</span>;
67 msg.len := <span class="number">21</span>;
68 _ := <span class="ty">XCHG</span>(ready, <span class="number">1</span>); <span class="comment">(* publish *)</span>
69<span class="kw">end</span>;
70
71<span class="kw">proc</span> main*;
72<span class="kw">var</span> t: ^Thread.Thread; err: <span class="ty">ERROR</span>;
73<span class="kw">begin</span>
74 t, err := Thread.spawn(producer, <span class="ty">nil</span>);
75 <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>;
76 <span class="kw">while</span> <span class="ty">XADD</span>(ready, <span class="number">0</span>) = <span class="number">0</span> <span class="kw">do</span> Sys.yield; <span class="kw">end</span>; <span class="comment">(* wait for it *)</span>
77 Out.int(msg.id); Out.char(<span class="string">&#x27; &#x27;</span>); Out.str(msg.text[<span class="number">0</span>..msg.len]); Out.ln;
78 Thread.join(t);
79<span class="kw">end</span>;
80
81<span class="kw">end</span> Publish.</code></pre>
82<pre class="output"><code>7 built before the flag
83</code></pre>
84<p>The reader's loop makes no ordinary read of <code>ready</code>: it can't be kept in a register and read once, which is the danger of <code>while ready = 0 do end</code>. And the write of <code>msg</code> can't be delayed past the <code>XCHG</code>.</p>
85<h2>The same with a fence</h2>
86<p><code>FENCE</code> is a full memory barrier: it orders the program's ordinary accesses against those of other processors and devices. With volatile accesses for the flag and a fence between the data and the flag, the same handoff works. This is the form device code takes, as in the last lesson.</p>
87<div class="file"><span>Fenced.raz</span></div><pre class="code"><code><span class="kw">module</span> Fenced;
88<span class="kw">import</span> Out, Sys, Thread;
89<span class="kw">import</span> SYSTEM;
90
91<span class="kw">var</span>
92 data: <span class="ty">INT</span>; <span class="comment">(* ordinary *)</span>
93 flag: <span class="ty">INT</span>; <span class="comment">(* only reached through a volatile pointer *)</span>
94
95<span class="kw">proc</span> producer(_arg: ^<span class="ty">U8</span>);
96<span class="kw">var</span> f: ^<span class="kw">VOLATILE</span> <span class="ty">INT</span>;
97<span class="kw">begin</span>
98 f := ^<span class="kw">VOLATILE</span> <span class="ty">INT</span>(SYSTEM.<span class="ty">ADR</span>(flag));
99 Sys.sleep(<span class="number">10</span>);
100 data := <span class="number">1234</span>;
101 FENCE; <span class="comment">(* data is written before the flag is *)</span>
102 f^ := <span class="number">1</span>;
103<span class="kw">end</span>;
104
105<span class="kw">proc</span> main*;
106<span class="kw">var</span> t: ^Thread.Thread; err: <span class="ty">ERROR</span>; f: ^<span class="kw">VOLATILE</span> <span class="ty">INT</span>;
107<span class="kw">begin</span>
108 f := ^<span class="kw">VOLATILE</span> <span class="ty">INT</span>(SYSTEM.<span class="ty">ADR</span>(flag));
109 t, err := Thread.spawn(producer, <span class="ty">nil</span>);
110 <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>;
111 <span class="kw">while</span> f^ = <span class="number">0</span> <span class="kw">do</span> Sys.yield; <span class="kw">end</span>;
112 FENCE; <span class="comment">(* and read after the flag is seen *)</span>
113 Out.int(data); Out.ln;
114 Thread.join(t);
115<span class="kw">end</span>;
116
117<span class="kw">end</span> Fenced.</code></pre>
118<pre class="output"><code>1234
119</code></pre>
120<p>Both sides need a fence. A fence on the writer only says the data is written first; the reader must not read <code>data</code> before it has seen the flag.</p>
121<h2>The version that is not guaranteed</h2>
122<p>This is what *not* to write, and it is the most common bug in this area:</p>
123<pre class="code"><code>var data, ready: INT;
124
125(* thread A *) data := 42; ready := 1;
126(* thread B *) while ready = 0 do end; use(data);</code></pre>
127<p>Both threads use ordinary accesses to shared variables. B's loop may read <code>ready</code> once into a register and spin forever; A's two writes may reach memory in either order; B may read <code>data</code> before the flag, or an old copy. On a particular machine with a particular compiler it may well work, until it is changed. The language says it holds no particular value, and it means it.</p>
128<h2>The lesson of the three versions</h2>
129<ul><li>Shared and written by someone: reach it through an atomic, a volatile pointer or a fence, every time, on both sides.</li><li>To hand over a bundle, publish a single atomic word *after* writing the bundle, and read the bundle only *after* seeing the word.</li><li>Everything under a <code>Lock</code> or a <code>Mutex</code> is ordered by the lock itself, so the data it guards can be ordinary variables. That is the simplest discipline, and the one to prefer until it is measured to be too slow.</li></ul><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="atomics.html">&larr; Atomics</a><a href="index.html">Contents</a><a class="next" href="lockfree.html">A lock-free stack &rarr;</a></div></article></div>
130</main>
131<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer>
132</body>
133</html>