2

golang happen before 的保证原则

 3 years ago
source link: https://studygolang.com/articles/33040
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1) 单线程

2) Init 函数

如果包P1中导入了包P2,则P2中的init函数Happens Before 所有P1中的操作

main函数Happens After 所有的init函数

3) Goroutine

Goroutine的创建Happens Before所有此Goroutine中的操作

Goroutine的销毁Happens After所有此Goroutine中的操作

4) Channel

对一个元素的send操作Happens Before对应的receive 完成操作  ,  [先发后接]

对channel的close操作Happens Before receive 端的收到关闭通知操作  [先关后接,接到零值]

对于无缓冲channel(unbuffered Channel),对一个元素的receive 操作Happens Before对应的send完成操作  [先接后发]

对于Buffered Channel,假设Channel 的buffer 大小为C,那么对第k个元素的receive操作,Happens Before第k+C个send完成操作。可以看出上一条Unbuffered Channel规则就是这条规则C=0时的特例  [先接后发]

5) Lock

Go里面有Mutex和RWMutex两种锁,RWMutex除了支持互斥的Lock/Unlock,还支持共享的RLock/RUnlock。

对于一个Mutex/RWMutex,设n < m,则第n个Unlock操作Happens Before第m个Lock操作。

对于一个RWMutex,存在数值n,RLock操作Happens After 第n个UnLock,其对应的RUnLock Happens Before 第n+1个Lock操作。

简单理解就是这一次的Lock总是Happens After上一次的Unlock,读写锁的RLock HappensAfter上一次的UnLock,其对应的RUnlock Happens Before 下一次的Lock。

有疑问加站长微信联系(非本文作者)

eUjI7rn.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK