1
0
mirror of https://github.com/chai2010/advanced-go-programming-book.git synced 2025-05-24 04:22:22 +00:00

Merge pull request #362 from wanyaoqi/master

更正附录关于《顺序一致性内存模型》例子
This commit is contained in:
chai2010 2018-09-24 06:27:24 +08:00 committed by GitHub
commit 89285eb1fb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -199,47 +199,43 @@ func main() {
## 不同Goroutine之间不满足顺序一致性内存模型
因为在不同的Goroutinemain函数可能无法观测到done的状态变化, 那么for循环会陷入死循环
因为在不同的Goroutinemain函数中无法保证能打印出`hello, world`:
```go
var msg string
var done bool = false
var done bool
func setup() {
msg = "hello, world"
done = true
}
func main() {
runtime.GOMAXPROCS(1)
go func() {
msg = "hello, world"
done = true
}()
for {
if done {
println(msg)
break
}
go setup()
for !done {
}
println(msg)
}
```
解决的办法是用显同步:
解决的办法是用显式同步:
```go
var msg string
var done = make(chan bool)
func setup() {
msg = "hello, world"
done <- true
}
func main() {
runtime.GOMAXPROCS(1)
go func() {
msg = "hello, world"
done <- true
}()
go setup()
<-done
println(msg)
}
```
msg的写入是在channel发送之前所以能保证打印`hello, world`
## 闭包错误引用同一个变量