raz / site / content / advanced / 16-ordering.txt

107 lines · 4.8 KiB · raw · history · last change a5145f64

1title: Ordering and publication
2part: Shared memory
3summary: Why a flag isn't enough, what FENCE and the atomics order, and the pattern that works.
4---
5Atomics 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?
6
7The report is careful. Only volatile accesses, `CAS`, `XCHG`, `XADD` and `FENCE` 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 `FENCE` 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.
8
9In plain words: two threads that share an ordinary variable with no atomic, volatile or fence between them get no guarantee about what each sees.
10
11## The pattern that is guaranteed: publish through an atomic
12
13The 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. `XCHG` is the store; `XADD(p, 0)` 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.
14
15```raz Publish run
16module Publish;
17import Out, Sys, Thread;
18import SYSTEM;
19
20type Message = record id: INT; text: [32]U8; len: INT; end;
21
22var
23 msg: Message; (* ordinary memory, written once, then published *)
24 ready: INT; (* the flag: only touched by atomics *)
25
26proc producer(_arg: ^U8);
27begin
28 Sys.sleep(10);
29 msg.id := 7;
30 msg.text := "built before the flag";
31 msg.len := 21;
32 _ := XCHG(ready, 1); (* publish *)
33end;
34
35proc main*;
36var t: ^Thread.Thread; err: ERROR;
37begin
38 t, err := Thread.spawn(producer, nil);
39 if err # nil then Out.str(MSG(err)); Out.ln; return; end;
40 while XADD(ready, 0) = 0 do Sys.yield; end; (* wait for it *)
41 Out.int(msg.id); Out.char(' '); Out.str(msg.text[0..msg.len]); Out.ln;
42 Thread.join(t);
43end;
44
45end Publish.
46```
47
48The reader's loop makes no ordinary read of `ready`: it can't be kept in a register and read once, which is the danger of `while ready = 0 do end`. And the write of `msg` can't be delayed past the `XCHG`.
49
50## The same with a fence
51
52`FENCE` 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.
53
54```raz Fenced run
55module Fenced;
56import Out, Sys, Thread;
57import SYSTEM;
58
59var
60 data: INT; (* ordinary *)
61 flag: INT; (* only reached through a volatile pointer *)
62
63proc producer(_arg: ^U8);
64var f: ^VOLATILE INT;
65begin
66 f := ^VOLATILE INT(SYSTEM.ADR(flag));
67 Sys.sleep(10);
68 data := 1234;
69 FENCE; (* data is written before the flag is *)
70 f^ := 1;
71end;
72
73proc main*;
74var t: ^Thread.Thread; err: ERROR; f: ^VOLATILE INT;
75begin
76 f := ^VOLATILE INT(SYSTEM.ADR(flag));
77 t, err := Thread.spawn(producer, nil);
78 if err # nil then Out.str(MSG(err)); Out.ln; return; end;
79 while f^ = 0 do Sys.yield; end;
80 FENCE; (* and read after the flag is seen *)
81 Out.int(data); Out.ln;
82 Thread.join(t);
83end;
84
85end Fenced.
86```
87
88Both sides need a fence. A fence on the writer only says the data is written first; the reader must not read `data` before it has seen the flag.
89
90## The version that is not guaranteed
91
92This is what *not* to write, and it is the most common bug in this area:
93
94```text
95var data, ready: INT;
96
97(* thread A *) data := 42; ready := 1;
98(* thread B *) while ready = 0 do end; use(data);
99```
100
101Both threads use ordinary accesses to shared variables. B's loop may read `ready` once into a register and spin forever; A's two writes may reach memory in either order; B may read `data` 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.
102
103## The lesson of the three versions
104
105- Shared and written by someone: reach it through an atomic, a volatile pointer or a fence, every time, on both sides.
106- To hand over a bundle, publish a single atomic word *after* writing the bundle, and read the bundle only *after* seeing the word.
107- Everything under a `Lock` or a `Mutex` 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.