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