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。
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。
相关文章推荐
- Golang内存模型解析-1
- JVM内存模型以及垃圾收集策略解析【续】
- JVM内存模型以及垃圾收集策略解析
- JVM内存模型及垃圾收集策略解析(一)
- JVM内存模型及垃圾收集策略解析
- JVM内存模型及垃圾收集策略解析
- MSVC++ 对象内存模型深入解析与具体应用
- JVM内存模型及垃圾收集策略解析
- JVM内存模型及垃圾收集策略解析(一)
- JVM内存模型及垃圾收集策略解析
- JVM内存模型以及垃圾收集策略解析
- JVM内存模型及垃圾收集策略解析
- JVM内存模型及垃圾收集策略解析
- JVM内存模型及垃圾收集策略解析
- JVM内存模型及垃圾收集策略解析
- JVM内存模型及垃圾收集策略解析
- JVM内存模型以及垃圾收集策略解析(重要)
- JVM内存模型及垃圾收集策略解析(2)
- JVM内存模型及垃圾收集策略解析
- JVM内存模型及垃圾收集策略解析(1)