Contents
Notes on how the Go memory model orders reads and writes.
Memory model
Happens before
The model defines when reads and writes are ordered. Without a defined order, you cannot rely on result ordering.
For a write w to V to be observed by a read r:
rdoes not happen beforew, and- no other write
w'happens afterwand beforer.
For w to be the only value r can see (no concurrent conflicting writes):
whappens beforer, and- every other write to
Vhappens afterror beforew.
Variable initialization counts as a write in the memory model.
Reads and writes larger than one machine word may appear as several word-sized operations without a single total order (word size = width of a native integer operation on the CPU).
Synchronization
Package initialization
- If package
pimports packageq,q‘sinithappens beforep‘sinit. main.mainhappens after all packageinitfunctions.
Goroutines
- Starting a goroutine with
gohappens before that goroutine runs. - Goroutine exit is not guaranteed to happen before any other operation.
Channels
- A send on a channel happens before the corresponding receive completes on that channel.
- Closing a channel happens before a receive that returns the zero value because the channel is closed.
- On an unbuffered channel, a receive happens before the send completes.
1 | var c = make(chan int) |
- On a channel with capacity
c, the kth receive happens before the (k+c)th send completes.
1 | // often used to limit concurrency |
sync package
- For
sync.Mutexorsync.RWMutex, ifn < m, the nthUnlock()happens before the mthLock().There must be an
Unlockbetween twoLockcalls; otherwise the secondLockblocks forever.
RWMutex: multiple readers can hold the lock together; readers block writers; writers exclude everyone.
1 | var l sync.Mutex |
- For
sync.RWMutex, the nthUnlock()happens before anRLock()that returns after call n toUnlock, and the matchingRUnlock()happens before call n+1 toLock().
For any
RLockonl, there is an n such thatRLockreturns after the nthUnlock, and the matchingRUnlockhappens before the (n+1)thLock.
1 | // ordering sketch |
- Within a single
once.Do(f)invocation,freturning happens before any otheronce.Do(f)call returns.Concurrent
once.Do(f)calls: only the first runsf; the rest block untilfreturns.
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
