关于 golang 官网一段代码的疑惑

44次阅读

共计 667 个字符,预计需要花费 2 分钟才能阅读完成。

Golang 官网一段关于同步错误的代码示例:

var a string
var done bool

func setup() {
	a = "hello, world"
	done = true
}

func main() {go setup()
	for !done {	}
	print(a)
}

官网对这段代码的解析原文:As before, there is no guarantee that, in main, observing the write to done implies observing the write to a, so this program could print an empty string too. Worse, there is no guarantee that the write to done will ever be observed by main, since there are no synchronization events between the two threads. The loop in main is not guaranteed to finish.


print(a)可能会输出一个空字符串这个比较好理解,因为 CPU 指令重排的原因,done = true有可能先于 a = "hello world" 语句执行,所以出现了这种情况。

但是 for 语句有可能会陷入死循环的原因我理解不了,原因是什么?

我猜测的原因是(有可能不正确):
done = true的修改 CPU 只写入到了本地核心的 store buffer,没有同步给其它 CPU 核心,导致不同核心的缓存数据不一致,接而导致运行在其它核心的 main 协程看不到这个修改,所以陷入了死循环

希望有大神能解析下原因,谢谢~

正文完
 0