]> Cypherpunks.ru repositories - gostls13.git/blob - doc/go_mem.html
Factored out boilerplate from all html docs in doc directory:
[gostls13.git] / doc / go_mem.html
1 <!-- The Go Memory Model -->
2
3 <h2>Introduction</h2>
4
5 <p>
6 The Go memory model specifies the conditions under which
7 reads of a variable in one goroutine can be guaranteed to
8 observe values produced by writes to the same variable in a different goroutine.
9 </p>
10
11 <h2>Happens Before</h2>
12
13 <p>
14 Within a single goroutine, reads and writes must behave
15 as if they executed in the order specified by the program.
16 That is, compilers and processors may reorder the reads and writes
17 executed within a single goroutine only when the reordering
18 does not change the execution behavior within that goroutine.
19 Because of this reordering, the execution order observed
20 by one may differ from the order perceived
21 by another.  For example, if one goroutine
22 executes <code>a = 1; b = 2;</code>, a second goroutine might observe
23 the updated value of <code>b</code> before the updated value of <code>a</code>.
24 </p>
25
26 <p>
27 To specify the requirements on reads and writes, we define
28 <i>happens before</i>, a partial order on the execution
29 of memory operations in a Go program.  If event <span class="event">e<sub>1</sub></span> happens
30 before event <span class="event">e<sub>2</sub></span>, then we say that <span class="event">e<sub>2</sub></span> happens after <span class="event">e<sub>1</sub></span>.
31 Also, if <span class="event">e<sub>1</sub></span> does not happen before <span class="event">e<sub>2</sub></span> and does not happen
32 after <span class="event">e<sub>2</sub></span>, then we say that <span class="event">e<sub>1</sub></span> and <span class="event">e<sub>2</sub></span> happen concurrently.
33 </p>
34
35 <p>
36 Within a single goroutine, the happens before order is the
37 order specified by the program.
38 </p>
39
40 <p>
41 A read <span class="event">r</span> of a variable <code>v</code> is <i>allowed</i> to observe a write <span class="event">w</span> to <code>v</code>
42 if both of the following hold:
43 </p>
44
45 <ol>
46 <li><span class="event">w</span> happens before <span class="event">r</span>.</li>
47 <li>There is no other write <span class="event">w'</span> to <code>v</code> that happens
48     after <span class="event">w</span> but before <span class="event">r</span>.</li>
49 </ol>
50
51 <p>
52 To guarantee that a read <span class="event">r</span> of a variable <code>v</code> observes a
53 particular write <span class="event">w</span> to <code>v</code>, ensure that <span class="event">w</span> is the only
54 write <span class="event">r</span> is allowed to observe.
55 That is, <span class="event">r</span> is <i>guaranteed</i> to observe <span class="event">w</span> if both of the following hold:
56 </p>
57
58 <ol>
59 <li><span class="event">w</span> happens before <span class="event">r</span>.</li>
60 <li>Any other write to the shared variable <code>v</code>
61 either happens before <span class="event">w</span> or after <span class="event">r</span>.</li>
62 </ol>
63
64 <p>
65 This pair of conditions is stronger than the first pair;
66 it requires that there are no other writes happening
67 concurrently with <span class="event">w</span> or <span class="event">r</span>.
68 </p>
69
70 <p>
71 Within a single goroutine,
72 there is no concurrency, so the two definitions are equivalent:
73 a read <span class="event">r</span> observes the value written by the most recent write <span class="event">w</span> to <code>v</code>.
74 When multiple goroutines access a shared variable <code>v</code>,
75 they must use synchronization events to establish
76 happens-before conditions that ensure reads observe the
77 desired writes.
78 </p>
79
80 <p>
81 The initialization of variable <code>v</code> with the zero value
82 for <code>v</code>'s type behaves as a write in the memory model.
83 </p>
84
85 <p>
86 Reads and writes of values larger than a single machine word
87 behave as multiple machine-word-sized operations in an
88 unspecified order.
89 </p>
90
91 <h2>Synchronization</h2>
92
93 <h3>Initialization</h3>
94
95 <p>
96 Program initialization runs in a single goroutine, and
97 new goroutines created during initialization do not
98 start running until initialization ends.
99 </p>
100
101 <p class="rule">
102 If a package <code>p</code> imports package <code>q</code>, the completion of
103 <code>q</code>'s <code>init</code> functions happens before the start of any of <code>p</code>'s.
104 </p>
105
106 <p class="rule">
107 The start of the function <code>main.main</code> happens after
108 all <code>init</code> functions have finished.
109 </p>
110
111 <p class="rule">
112 The execution of any goroutines created during <code>init</code>
113 functions happens after all <code>init</code> functions have finished.
114 </p>
115
116 <h3>Goroutine creation</h3>
117
118 <p class="rule">
119 The <code>go</code> statement that starts a new goroutine
120 happens before the goroutine's execution begins.
121 </p>
122
123 <p>
124 For example, in this program:
125 </p>
126
127 <pre>
128 var a string;
129
130 func f() {
131         print(a);
132 }
133
134 func hello() {
135         a = "hello, world";
136         go f();
137 }
138 </pre>
139
140 <p>
141 calling <code>hello</code> will print <code>"hello, world"</code>
142 at some point in the future (perhaps after <code>hello</code> has returned).
143 </p>
144
145 <h3>Channel communication</h3>
146
147 <p>
148 Channel communication is the main method of synchronization
149 between goroutines.  Each send on a particular channel
150 is matched to a corresponding receive from that channel,
151 usually in a different goroutine.
152 </p>
153
154 <p class="rule">
155 A send on a channel happens before the corresponding
156 receive from that channel completes.
157 </p>
158
159 <p>
160 For example, this program:
161 </p>
162
163 <pre>
164 var c = make(chan int, 10);
165 var a string;
166
167 func f() {
168         a = "hello, world";
169         c &lt;- 0;
170 }
171
172 func main() {
173         go f();
174         &lt;-c;
175         print(a);
176 }
177 </pre>
178
179 <p>
180 is guaranteed to print <code>"hello, world"</code>.  The write to <code>a</code>
181 happens before the send on <code>c</code>, which happens before
182 the corresponding receive on <code>c</code> completes, which happens before
183 the <code>print</code>.
184 </p>
185
186 <p class="rule">
187 A receive from an unbuffered channel happens before
188 the send on that channel completes.
189 </p>
190
191 <p>
192 For example, this program:
193 </p>
194
195 <pre>
196 var c = make(chan int);
197 var a string;
198
199 func f() {
200         a = "hello, world";
201         &lt;-c;
202 }
203 </pre>
204
205 <pre>
206 func main() {
207         go f();
208         c &lt;- 0;
209         print(a);
210 }
211 </pre>
212
213 <p>
214 is also guaranteed to print "hello, world".  The write to <code>a</code>
215 happens before the receive on <code>c</code>, which happens before
216 the corresponding send on <code>c</code> completes, which happens
217 before the <code>print</code>.
218 </p>
219
220 <p>
221 If the channel were buffered (e.g., <code>c = make(chan int, 1)</code>)
222 then the program would not be guaranteed to print
223 <code>"hello, world"</code>.  (It might print the empty string;
224 it cannot print <code>"hello, sailor"</code>, nor can it crash.)
225 </p>
226
227 <h3>Locks</h3>
228
229 <p>
230 The <code>sync</code> package implements two lock data types,
231 <code>sync.Mutex</code> and <code>sync.RWMutex</code>.
232 </p>
233
234 <p class="rule">
235 For any <code>sync.Mutex</code> variable <code>l</code> and <i>n</i> &lt; <i>m</i>,
236 the <i>n</i>'th call to <code>l.Unlock()</code> happens before the <i>m</i>'th call to <code>l.Lock()</code> returns.
237 </p>
238
239 <p>
240 For example, this program:
241 </p>
242
243 <pre>
244 var l sync.Mutex;
245 var a string;
246
247 func f() {
248         a = "hello, world";
249         l.Unlock();
250 }
251
252 func main() {
253         l.Lock();
254         go f();
255         l.Lock();
256         print(a);
257 }
258 </pre>
259
260 <p>
261 is guaranteed to print <code>"hello, world"</code>.
262 The first call to <code>l.Unlock()</code> (in <code>f</code>) happens
263 before the second call to <code>l.Lock()</code> (in <code>main</code>) returns,
264 which happens before the <code>print</code>.
265 </p>
266
267 <p>
268 TODO(rsc): <code>sync.RWMutex</code>.
269 </p>
270
271 <h3>Once</h3>
272
273 <p>
274 The <code>once</code> package provides a safe mechanism for
275 initialization in the presence of multiple goroutines.
276 Multiple threads can execute <code>once.Do(f)</code> for a particular <code>f</code>,
277 but only one will run <code>f()</code>, and the other calls block
278 until <code>f()</code> has returned.
279 </p>
280
281 <p>
282 A single call to <code>f()</code> happens before <code>once.Do(f)</code> returns.
283 </p>
284
285 <p>
286 For example, in this program:
287 </p>
288
289 <pre>
290 var a string;
291
292 func setup() {
293         a = "hello, world";
294 }
295
296 func doprint() {
297         once.Do(setup);
298         print(a);
299 }
300
301 func twoprint() {
302         go doprint();
303         go doprint();
304 }
305 </pre>
306
307 <p>
308 calling <code>twoprint</code> causes <code>"hello, world"</code> to be printed twice.
309 The first call to <code>twoprint</code> runs <code>setup</code> once.
310 </p>
311
312 <h2>Incorrect synchronization</h2>
313
314 <p>
315 Note that a read <span class="event">r</span> may observe the value written by a write <span class="event">w</span>
316 that happens concurrently with <span class="event">r</span>.
317 Even if this occurs, it does not imply that reads happening after <span class="event">r</span>
318 will observe writes that happened before <span class="event">w</span>.
319 </p>
320
321 <p>
322 For example, in this program:
323 </p>
324
325 <pre>
326 var a, b int;
327
328 func f() {
329         a = 1;
330         b = 2;
331 }
332
333 func g() {
334         print(b);
335         print(a);
336 }
337
338 func main() {
339         go f();
340         g();
341 }
342 </pre>
343
344 <p>
345 it can happen that <code>g</code> prints <code>2</code> and then <code>0</code>.
346 </p>
347
348 <p>
349 This fact invalidates a few obvious idioms.
350 </p>
351
352 <p>
353 Double-checked locking is an attempt to avoid the overhead of synchronization.
354 For example, the <code>twoprint</code> program above, might be
355 incorrectly written as:
356 </p>
357
358 <pre>
359 var a string;
360 var done bool;
361
362 func setup() {
363         a = "hello, world";
364         done = true;
365 }
366
367 func doprint() {
368         if !done {
369                 once.Do(setup);
370         }
371         print(a);
372 }
373
374 func twoprint() {
375         go doprint();
376         go doprint();
377 }
378 </pre>
379
380 <p>
381 but there is no guarantee that, in <code>doprint</code>, observing the write to <code>done</code>
382 implies observing the write to <code>a</code>.  This
383 version can (incorrectly) print an empty string
384 instead of <code>"hello, world"</code>.
385 </p>
386
387 <p>
388 Another incorrect idiom is busy waiting for a value, as in:
389 </p>
390
391 <pre>
392 var a string;
393 var done bool;
394
395 func setup() {
396         a = "hello, world";
397         done = true;
398 }
399
400 func main() {
401         go setup();
402         for !done {
403         }
404         print(a);
405 }
406 </pre>
407
408 <p>
409 As before, there is no guarantee that, in <code>main</code>,
410 observing of the write to <code>done</code>
411 implies observing the write to <code>a</code>, so this program could
412 print an empty string too.
413 Worse, there is no guarantee that the write to <code>done</code> will ever
414 be observed by <code>main</code>, since there are no synchronization
415 events between the two threads.  The loop in <code>main</code> is not
416 guaranteed to finish.
417 </p>
418
419 <p>
420 There are subtler variants on this theme.  For example, in this program:
421 </p>
422
423 <pre>
424 type T struct {
425         msg string;
426 }
427
428 var g *T;
429
430 func setup() {
431         t := new(T);
432         t.msg = "hello, world";
433         g = t;
434 }
435
436 func main() {
437         go setup();
438         for g == nil {
439         }
440         print(g.msg);
441 }
442 </pre>
443
444 <p>
445 Even if <code>main</code> observes <code>g != nil</code> and exits its loop,
446 there is no guarantee that it will observe the initialized
447 value for <code>g.msg</code>.
448 </p>
449
450 <p>
451 In all these examples, the solution is the same:
452 use explicit synchronization.
453 </p>
454
455 </div>
456
457 <div id="footer">
458 <p>Except as noted, this content is
459    licensed under <a href="http://creativecommons.org/licenses/by/3.0/">
460    Creative Commons Attribution 3.0</a>.
461 </div>
462
463
464 </body>
465 </html>
466