您的位置:首页 > 编程语言 > Go语言

Golang内存模型解析-2

2017-03-30 10:57 399 查看
Channel通信:

1)Channel的发送和接收,满足Happen-before。(废话)

var c = make(chan int,10)
var a string

func f() {
a = "hello, world"
c <- 0
}

func main() {
go f()
<-c
print(a)
}
上述代码中,a的赋值happen-before写入channel,写入channel happen-before读取channel,读取channel happen-before print

把<-c替换成close,同样结果一样。因为 

                The closing of a channel happensbefore a receive that returns a zero value because the channel is closed.

 说的比较抽象,我的理解是close后,会存在一个阻塞的receive,从而读取所有未发送的数据。

 

2)对于无缓存channel,receive happen-before send。即先阻塞,后传值。带缓存的channel的close不会阻塞,所以无法保证happen-before

var c = make(chan int)
var a string

func f() {
a = "hello, world"
<-c
}
func main() {
go f()
c <- 0
print(a)
}
上述代码回正确打印helloworld,因为a的赋值happen-before receive, receive happen-before send。如果有缓存则不保证正确打印

3)对于缓存容量为C的channel,第k次receive happen-before
k+C次send。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: