go_mem.html 13 KB

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