提示:目录自动生成
文章目录
前言
提示:本文要记录的大概内容:
golang的happens-before原则,前面一个操作的结果对后续操作是可见的,在保证了这一原则下就能保证内存可见性的正确性,
提示:以下是本篇文章正文内容
一、happens-before原则
1. Initialization
If a package p imports package q, the completion of q’s init functions happens before the start of any of p’s.
2. Goroutine creation
The go statement that starts a new goroutine happens before the goroutine’s execution begins.
3. Goroutine destruction
The exit of a goroutine is not guaranteed to happen before any event in the program.
4. Channel communiaction
4.1
A send on a channel happens before the corresponding receive from that channel completes.
4.2
The closing of a channel happens before a receive that returns a zero value because the channel is closed.
4.3
A receive from an unbuffered channel happens before the send on that channel completes.
4.4
The kth receive on a channel with capacity C happens before the k+Cth send from that channel completes.
5. Locks
5.1
For any sync.Mutex or sync.RWMutex variable l and n < m, call n of l.Unlock() happens before call m of l.Lock() returns.
5.2
For any call to l.RLock on a sync.RWMutex variable l, there is an n such that the l.RLock happens (returns) after call n to l.Unlock and the matching l.RUnlock happens before call n+1 to l.Lock.
6. Once
A single call of f() from once.Do(f) happens (returns) before any call of once.Do(f) returns.