| 1 | title: A ring buffer between threads |
| 2 | part: Shared memory |
| 3 | summary: A single-producer, single-consumer queue, put together from what the tour has covered. |
| 4 | --- |
| 5 | 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. |
| 6 | |
| 7 | ## The design |
| 8 | |
| 9 | The 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 | |
| 11 | The 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 | |
| 13 | The 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 |
| 18 | module Ring; |
| 19 | import Sys; |
| 20 | import SYSTEM; |
| 21 | |
| 22 | const Size* = 64; |
| 23 | |
| 24 | type |
| 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 *) |
| 31 | proc put*(r: ^Ring; v: INT); |
| 32 | var t: INT; |
| 33 | begin |
| 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 *) |
| 38 | end; |
| 39 | |
| 40 | (* the next value, waiting while the ring is empty *) |
| 41 | proc take*(r: ^Ring): INT; |
| 42 | var h, v: INT; |
| 43 | begin |
| 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; |
| 49 | end; |
| 50 | |
| 51 | end Ring. |
| 52 | ``` |
| 53 | |
| 54 | ## Using it |
| 55 | |
| 56 | 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. |
| 57 | |
| 58 | ```raz Pipe run |
| 59 | module Pipe; |
| 60 | import Out, Fmt, Ring, Thread; |
| 61 | import SYSTEM; |
| 62 | |
| 63 | const Count = 100000; |
| 64 | |
| 65 | var |
| 66 | ring: Ring.Ring; |
| 67 | sum, outOfOrder: INT; |
| 68 | |
| 69 | proc producer(_arg: ^U8); |
| 70 | var i: INT; |
| 71 | begin |
| 72 | for i := 1 to Count do Ring.put(SYSTEM.ADR(ring), i); end; |
| 73 | end; |
| 74 | |
| 75 | proc consumer(_arg: ^U8); |
| 76 | var i, v: INT; |
| 77 | begin |
| 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; |
| 83 | end; |
| 84 | |
| 85 | proc main*; |
| 86 | var p, c: ^Thread.Thread; err: ERROR; |
| 87 | begin |
| 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)]); |
| 96 | end; |
| 97 | |
| 98 | end Pipe. |
| 99 | ``` |
| 100 | |
| 101 | The 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 | |
| 110 | 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 `put` and `take` should make, and the sort a reader should demand. |
| 111 | |
| 112 | ## Where next |
| 113 | |
| 114 | That 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. |