Golang内存模型解析-2

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)对于缓存容量为Cchannel,第kreceive happen-before k+Csend

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值