【发布时间】:2021-06-14 19:09:07
【问题描述】:
我正在尝试理解来自The Go Memory Model 的同步代码不正确的示例。
双重检查锁定是一种避免同步开销的尝试。例如,twoprint 程序可能被错误地写成:
var a string
var done bool
func setup() {
a = "hello, world"
done = true
}
func doprint() {
if !done {
once.Do(setup)
}
print(a)
}
func twoprint() {
go doprint()
go doprint()
}
但不能保证,在
doprint中,观察到完成的写入意味着观察到对a的写入。这个版本可以(错误地)打印一个空字符串而不是"hello, world"。
“hello world”打印空字符串的详细原因是什么?我运行了这段代码大约五次,每次都打印“hello world”。
编译器会交换一行a = "hello, world" 和done = true 以进行优化吗?只有在这种情况下,我才能理解为什么会打印一个空字符串。
非常感谢! 在底部,我附上了测试的更改代码。
package main
import(
"fmt"
"sync"
)
var a string
var done bool
var on sync.Once
func setup() {
a = "hello, world"
done = true
}
func doprint() {
if !done {
on.Do(setup)
}
fmt.Println(a)
}
func main() {
go doprint()
go doprint()
select{}
}
【问题讨论】:
-
你可以运行你的代码 100 万次,总是得到“hello world”,这证明不了。编译器不允许交换这两行并且不这样做。问题是不同的 goroutine 看到不同的世界除非正确同步。仅仅因为在
func setup中,a 在 done 设置为 true 之前设置为“hello world”,并不意味着这个顺序会被不同的 goroutine 看到。不同的、未同步或不同步的 goroutine 看到了一个不同的世界。这就是现代 CPU 架构的工作原理。
标签: go synchronization race-condition double-checked-locking