raz / site / content / advanced / 18-ring.txt

120 lines · 4.9 KiB · raw · history · last change a5145f64

1title: A ring buffer between threads
2part: Shared memory
3summary: A single-producer, single-consumer queue, put together from what the tour has covered.
4---
5To 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.
6
7## The design
8
9The queue is a fixed array of slots, used as a circle, and two counters that only ever grow: `tail`, the number of items the producer has put in, and `head`, the number the consumer has taken out. The item `n` lives in slot `n mod Size`. The queue is empty when the two are equal, and full when they differ by `Size`.
10
11The design rule is that **each counter has exactly one writer**. Only the producer changes `tail`; only the consumer changes `head`. 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 `CAS` is needed, because there is never a race to resolve: only a handoff.
12
13The handoff is the publish pattern of the ordering lesson. The producer writes the slot, then publishes it with an atomic store of `tail`; the consumer sees the new `tail` with an atomic load and only then reads the slot. In the other direction, the consumer frees a slot by storing `head`, and the producer only reuses it after loading `head` and seeing that.
14
15## The module
16
17```raz Ring
18module Ring;
19import Sys;
20import SYSTEM;
21
22const Size* = 64;
23
24type
25 Ring* = record
26 slots: [Size]INT;
27 head, tail: INT; (* items taken, items put; each has one writer *)
28 end;
29
30(* v into the ring, waiting while it is full *)
31proc put*(r: ^Ring; v: INT);
32var t: INT;
33begin
34 t := r^.tail; (* mine: an ordinary read *)
35 while t - XADD(r^.head, 0) = Size do Sys.yield; end; (* full *)
36 r^.slots[t mod Size] := v;
37 _ := XCHG(r^.tail, t + 1); (* publish the slot *)
38end;
39
40(* the next value, waiting while the ring is empty *)
41proc take*(r: ^Ring): INT;
42var h, v: INT;
43begin
44 h := r^.head; (* mine *)
45 while XADD(r^.tail, 0) = h do Sys.yield; end; (* empty *)
46 v := r^.slots[h mod Size];
47 _ := XCHG(r^.head, h + 1); (* give the slot back *)
48 return v;
49end;
50
51end Ring.
52```
53
54## Using it
55
56One 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.
57
58```raz Pipe run
59module Pipe;
60import Out, Fmt, Ring, Thread;
61import SYSTEM;
62
63const Count = 100000;
64
65var
66 ring: Ring.Ring;
67 sum, outOfOrder: INT;
68
69proc producer(_arg: ^U8);
70var i: INT;
71begin
72 for i := 1 to Count do Ring.put(SYSTEM.ADR(ring), i); end;
73end;
74
75proc consumer(_arg: ^U8);
76var i, v: INT;
77begin
78 for i := 1 to Count do
79 v := Ring.take(SYSTEM.ADR(ring));
80 if v # i then INC(outOfOrder); end;
81 sum := sum + v;
82 end;
83end;
84
85proc main*;
86var p, c: ^Thread.Thread; err: ERROR;
87begin
88 p, err := Thread.spawn(producer, nil);
89 if err # nil then Out.str(MSG(err)); Out.ln; return; end;
90 c, err := Thread.spawn(consumer, nil);
91 if err # nil then Out.str(MSG(err)); Out.ln; return; end;
92 Thread.join(p);
93 Thread.join(c);
94 Fmt.print("{} items, sum {}, {} out of order\n",
95 [Fmt.int(Count), Fmt.int(sum), Fmt.int(outOfOrder)]);
96end;
97
98end Pipe.
99```
100
101The sum of 1 to 100000 is 5000050000, and nothing arrives out of order. `sum` and `outOfOrder` are written only by the consumer thread and read by `main` after `Thread.join`, which is the synchronization that makes them visible: a join is the thread's end, observed.
102
103## What it used
104
105- **Modules** (`Ring`, with its record's own fields unexported).
106- **Atomics** for the handoff, and an ordering argument for why a slot is complete when its counter moves.
107- **Threads** from `Thread`, with no C in the program.
108- **The checks**, which stay on: `slots[t mod Size]` is an indexed array access that can't leave the array, whatever the counters do.
109
110It 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 `put` and `take` should make, and the sort a reader should demand.
111
112## Where next
113
114That is the end of the tour. A few places to continue:
115
116- **[The report](../spec.html)** defines the language, and is short enough to read through.
117- **`doc/compiler.md`** 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.
118- **`lib/`** is the library, in raz. Each module's own `main` is its test. Reading `Heap`, `Map`, `Opt` and `Thread` is the best remaining education.
119- **`tools/Doc.raz`** prints what a module exports with its comments: `raz -o Doc tools/Doc.raz && ./Doc lib/Str.raz`.
120- **`examples/`** holds small programs with the output each should give, and `conform/` holds what any implementation must do.