raz / site / public / advanced / ring.html

141 lines · 11.2 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>A ring buffer between threads - 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 ring buffer between threads - 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">A lock-free stack</a></li>
45<li><a href="ring.html" aria-current="page">A ring buffer between threads</a></li>
46</ol></aside><article><p class="kicker">Shared memory &middot; lesson 18 of 18</p><h1>A ring buffer between threads</h1>
47<p>To finish, here is a small piece of real concurrent code that uses nearly everything in this part of the tour: a queue through which one thread sends numbers to another, with no lock and no allocation.</p>
48<h2>The design</h2>
49<p>The queue is a fixed array of slots, used as a circle, and two counters that only ever grow: <code>tail</code>, the number of items the producer has put in, and <code>head</code>, the number the consumer has taken out. The item <code>n</code> lives in slot <code>n mod Size</code>. The queue is empty when the two are equal, and full when they differ by <code>Size</code>.</p>
50<p>The design rule is that <strong>each counter has exactly one writer</strong>. Only the producer changes <code>tail</code>; only the consumer changes <code>head</code>. Each thread reads its own counter with an ordinary read, since nobody else changes it, and the other thread's with an atomic one. No <code>CAS</code> is needed, because there is never a race to resolve: only a handoff.</p>
51<p>The handoff is the publish pattern of the ordering lesson. The producer writes the slot, then publishes it with an atomic store of <code>tail</code>; the consumer sees the new <code>tail</code> with an atomic load and only then reads the slot. In the other direction, the consumer frees a slot by storing <code>head</code>, and the producer only reuses it after loading <code>head</code> and seeing that.</p>
52<h2>The module</h2>
53<div class="file"><span>Ring.raz</span></div><pre class="code"><code><span class="kw">module</span> Ring;
54<span class="kw">import</span> Sys;
55<span class="kw">import</span> SYSTEM;
56
57<span class="kw">const</span> Size* = <span class="number">64</span>;
58
59<span class="kw">type</span>
60 Ring* = <span class="kw">record</span>
61 slots: [Size]<span class="ty">INT</span>;
62 head, tail: <span class="ty">INT</span>; <span class="comment">(* items taken, items put; each has one writer *)</span>
63 <span class="kw">end</span>;
64
65<span class="comment">(* v into the ring, waiting while it is full *)</span>
66<span class="kw">proc</span> put*(r: ^Ring; v: <span class="ty">INT</span>);
67<span class="kw">var</span> t: <span class="ty">INT</span>;
68<span class="kw">begin</span>
69 t := r^.tail; <span class="comment">(* mine: an ordinary read *)</span>
70 <span class="kw">while</span> t - <span class="ty">XADD</span>(r^.head, <span class="number">0</span>) = Size <span class="kw">do</span> Sys.yield; <span class="kw">end</span>; <span class="comment">(* full *)</span>
71 r^.slots[t <span class="kw">mod</span> Size] := v;
72 _ := <span class="ty">XCHG</span>(r^.tail, t + <span class="number">1</span>); <span class="comment">(* publish the slot *)</span>
73<span class="kw">end</span>;
74
75<span class="comment">(* the next value, waiting while the ring is empty *)</span>
76<span class="kw">proc</span> take*(r: ^Ring): <span class="ty">INT</span>;
77<span class="kw">var</span> h, v: <span class="ty">INT</span>;
78<span class="kw">begin</span>
79 h := r^.head; <span class="comment">(* mine *)</span>
80 <span class="kw">while</span> <span class="ty">XADD</span>(r^.tail, <span class="number">0</span>) = h <span class="kw">do</span> Sys.yield; <span class="kw">end</span>; <span class="comment">(* empty *)</span>
81 v := r^.slots[h <span class="kw">mod</span> Size];
82 _ := <span class="ty">XCHG</span>(r^.head, h + <span class="number">1</span>); <span class="comment">(* give the slot back *)</span>
83 <span class="kw">return</span> v;
84<span class="kw">end</span>;
85
86<span class="kw">end</span> Ring.</code></pre>
87<h2>Using it</h2>
88<p>One thread sends the numbers 1 to 100000 through a ring of 64 slots, so it is stopped by a full ring many times over and has to wait for the consumer. The consumer checks each number arrives in order, and adds them.</p>
89<div class="file"><span>Pipe.raz</span></div><pre class="code"><code><span class="kw">module</span> Pipe;
90<span class="kw">import</span> Out, Fmt, Ring, Thread;
91<span class="kw">import</span> SYSTEM;
92
93<span class="kw">const</span> Count = <span class="number">100000</span>;
94
95<span class="kw">var</span>
96 ring: Ring.Ring;
97 sum, outOfOrder: <span class="ty">INT</span>;
98
99<span class="kw">proc</span> producer(_arg: ^<span class="ty">U8</span>);
100<span class="kw">var</span> i: <span class="ty">INT</span>;
101<span class="kw">begin</span>
102 <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> Count <span class="kw">do</span> Ring.put(SYSTEM.<span class="ty">ADR</span>(ring), i); <span class="kw">end</span>;
103<span class="kw">end</span>;
104
105<span class="kw">proc</span> consumer(_arg: ^<span class="ty">U8</span>);
106<span class="kw">var</span> i, v: <span class="ty">INT</span>;
107<span class="kw">begin</span>
108 <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> Count <span class="kw">do</span>
109 v := Ring.take(SYSTEM.<span class="ty">ADR</span>(ring));
110 <span class="kw">if</span> v # i <span class="kw">then</span> <span class="ty">INC</span>(outOfOrder); <span class="kw">end</span>;
111 sum := sum + v;
112 <span class="kw">end</span>;
113<span class="kw">end</span>;
114
115<span class="kw">proc</span> main*;
116<span class="kw">var</span> p, c: ^Thread.Thread; err: <span class="ty">ERROR</span>;
117<span class="kw">begin</span>
118 p, err := Thread.spawn(producer, <span class="ty">nil</span>);
119 <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>;
120 c, err := Thread.spawn(consumer, <span class="ty">nil</span>);
121 <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>;
122 Thread.join(p);
123 Thread.join(c);
124 Fmt.print(<span class="string">&quot;{} items, sum {}, {} out of order\n&quot;</span>,
125 [Fmt.int(Count), Fmt.int(sum), Fmt.int(outOfOrder)]);
126<span class="kw">end</span>;
127
128<span class="kw">end</span> Pipe.</code></pre>
129<pre class="output"><code>100000 items, sum 5000050000, 0 out of order
130</code></pre>
131<p>The sum of 1 to 100000 is 5000050000, and nothing arrives out of order. <code>sum</code> and <code>outOfOrder</code> are written only by the consumer thread and read by <code>main</code> after <code>Thread.join</code>, which is the synchronization that makes them visible: a join is the thread's end, observed.</p>
132<h2>What it used</h2>
133<ul><li><strong>Modules</strong> (<code>Ring</code>, with its record's own fields unexported).</li><li><strong>Atomics</strong> for the handoff, and an ordering argument for why a slot is complete when its counter moves.</li><li><strong>Threads</strong> from <code>Thread</code>, with no C in the program.</li><li><strong>The checks</strong>, which stay on: <code>slots[t mod Size]</code> is an indexed array access that can't leave the array, whatever the counters do.</li></ul>
134<p>It is not a finished library: it is one producer and one consumer, and a second of either breaks the one-writer rule. That is the sort of statement a comment above <code>put</code> and <code>take</code> should make, and the sort a reader should demand.</p>
135<h2>Where next</h2>
136<p>That is the end of the tour. A few places to continue:</p>
137<ul><li><strong><a href="../spec.html">The report</a></strong> defines the language, and is short enough to read through.</li><li><strong><code>doc/compiler.md</code></strong> in the sources is a guide to reading the compiler, file by file; it is a model of the style the project is written in.</li><li><strong><code>lib/</code></strong> is the library, in raz. Each module's own <code>main</code> is its test. Reading <code>Heap</code>, <code>Map</code>, <code>Opt</code> and <code>Thread</code> is the best remaining education.</li><li><strong><code>tools/Doc.raz</code></strong> prints what a module exports with its comments: <code>raz -o Doc tools/Doc.raz &amp;&amp; ./Doc lib/Str.raz</code>.</li><li><strong><code>examples/</code></strong> holds small programs with the output each should give, and <code>conform/</code> holds what any implementation must do.</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="lockfree.html">&larr; A lock-free stack</a><a href="index.html">Contents</a><a class="next" href="../spec.html">The report &rarr;</a></div></article></div>
138</main>
139<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer>
140</body>
141</html>