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