raz / site / content / advanced / 15-atomics.txt

171 lines · 5.7 KiB · raw · history · last change a5145f64

1title: Atomics
2part: Shared memory
3summary: XADD, XCHG and CAS; a compare-and-swap loop; a lock built from them.
4---
5A volatile access is one access. An atomic is one *indivisible* step: nothing can happen between its read and its write, so two threads using it can't lose each other's work. There are three, built into the language as procedures, and they are sequentially consistent on every target:
6
7| Call | Does |
8|---|---|
9| `XADD(p, x)` | adds `x` to `p` and returns the value before |
10| `XCHG(p, x)` | sets `p := x` and returns the value before |
11| `CAS(p, old, new)` | if `p = old`, sets `p := new` and returns `true`; otherwise `false` |
12
13`p` is a variable (or `q^` through a pointer `q`, even `^VOLATILE`) of type `INT`, `UINT` or a pointer type (`INT` or `UINT` for `XADD`); the atomic works on the variable itself, so no `ADR` is taken. A module that uses them says `import SYSTEM;`. They compile to single x86-64 instructions: `lock xadd`, `xchg` (which is always locked when it touches memory) and `lock cmpxchg`:
14
15```raz Ops
16module Ops;
17import SYSTEM;
18
19var counter: INT;
20
21proc main*;
22begin
23 _ := XADD(counter, 5);
24 _ := XCHG(counter, 100);
25 _ := CAS(counter, 100, 7);
26end;
27
28end Ops.
29```
30
31```sh
32$ raz -S Ops.raz | grep -i "lock\|xchg"
33```
34
35## What each one gives you
36
37`XADD` is a counter, or a ticket dispenser: every caller gets a different number. `XCHG` takes the old value and leaves a new one, which is a flag, a swap, or the release of a lock. `CAS` is the general one: "if nobody changed it since I looked, change it". Most lock-free code is a loop around it.
38
39```raz Tickets run
40module Tickets;
41import Out, Thread;
42import SYSTEM;
43
44var
45 next: INT; (* the next ticket to give out *)
46 seen: [4000]U8; (* which tickets were taken, one byte each *)
47
48proc work(_arg: ^U8);
49var i, t: INT;
50begin
51 for i := 1 to 1000 do
52 t := XADD(next, 1); (* a ticket no other thread gets *)
53 seen[t] := 1;
54 end;
55end;
56
57proc main*;
58var th: [4]^Thread.Thread; i, taken: INT; err: ERROR;
59begin
60 for i := 0 to 3 do
61 th[i], err := Thread.spawn(work, nil);
62 if err # nil then Out.str(MSG(err)); Out.ln; return; end;
63 end;
64 for i := 0 to 3 do Thread.join(th[i]); end;
65 for i := 0 to 3999 do taken := taken + seen[i]; end;
66 Out.int(next); Out.char(' '); Out.int(taken); Out.ln;
67end;
68
69end Tickets.
70```
71
72Four thousand tickets, four thousand different numbers, no two threads with the same one. Each thread writes into its own bytes of `seen`, so no plain write is shared.
73
74## A compare-and-swap loop
75
76Anything that can be computed from the old value can be made atomic with a loop around `CAS`: read the value, compute the new one, and try to swap it in; if someone got there first, read again. Here is an atomic maximum, which no single instruction does.
77
78```raz Peak run
79module Peak;
80import Out, Thread;
81import SYSTEM;
82
83var peak: INT;
84
85(* raises peak to v if v is bigger, however many threads call it *)
86proc raise(v: INT);
87var seen: INT;
88begin
89 seen := peak;
90 while seen < v do
91 if CAS(peak, seen, v) then return; end;
92 seen := peak; (* someone changed it: look again *)
93 end;
94end;
95
96proc work(arg: ^U8);
97var i, base: INT;
98begin
99 base := INT(arg);
100 for i := 0 to 999 do raise(base + i * 7 mod 1001); end;
101end;
102
103proc main*;
104var th: [4]^Thread.Thread; i: INT; err: ERROR;
105begin
106 for i := 0 to 3 do
107 th[i], err := Thread.spawn(work, ^U8(i * 1000));
108 if err # nil then Out.str(MSG(err)); Out.ln; return; end;
109 end;
110 for i := 0 to 3 do Thread.join(th[i]); end;
111 Out.int(peak); Out.ln;
112end;
113
114end Peak.
115```
116
117The result doesn't depend on how the threads interleave: it is the largest value any of them offered. That is the test of a correct atomic algorithm, and why this kind of code is written once, carefully, and used everywhere.
118
119## A lock, from first principles
120
121A lock is a word that is 0 when free and 1 when held. To take it, `CAS` it from 0 to 1; if that fails, someone holds it, so try again. To give it up, `XCHG` it back to 0. This is exactly the library's `Lock`, printed from `lib/Lock.raz`:
122
123```sh
124$ sed -n '/^type Lock/,/^proc main/p' $RAZLIB/Lock.raz | head -n -2
125```
126
127And here is a use of it: a structure with two fields that must stay in step, which no single atomic can protect.
128
129```raz Account run
130module Account;
131import Out, Lock, Thread;
132
133var
134 lock: Lock.Lock;
135 deposits, balance: INT; (* balance = 3 * deposits, always, under lock *)
136
137proc work(_arg: ^U8);
138var i: INT;
139begin
140 for i := 1 to 20000 do
141 Lock.take(lock);
142 INC(deposits);
143 INC(balance, 3);
144 Lock.give(lock);
145 end;
146end;
147
148proc main*;
149var th: [4]^Thread.Thread; i: INT; err: ERROR;
150begin
151 for i := 0 to 3 do
152 th[i], err := Thread.spawn(work, nil);
153 if err # nil then Out.str(MSG(err)); Out.ln; return; end;
154 end;
155 for i := 0 to 3 do Thread.join(th[i]); end;
156 Out.int(deposits); Out.char(' '); Out.int(balance); Out.ln;
157 if balance = 3 * deposits then Out.str("in step\n"); end;
158end;
159
160end Account.
161```
162
163A `Lock` spins, giving up the processor now and then, so it is for sections of a few instructions. `Thread.Mutex` sleeps on a futex, so it is for longer ones. A spinning lock held for a long time, or by a thread that was descheduled, burns processors; that is the price of its speed when contention is short.
164
165## Choosing
166
167- A counter, a ticket, a flag: `XADD` or `XCHG`.
168- A value computed from the old one: a `CAS` loop.
169- Several variables that must change together: a `Lock` or a `Mutex`. Don't try to be clever with several atomics; the one invariant spanning them is the thing that breaks.
170
171All three act on a word. For anything bigger, the thing you swap is a pointer to the bigger thing: the next lessons do exactly that.