Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于 “1.5.3 顺序一致性内存模型”中的疑问 #604

Open
JOJO0527 opened this issue Oct 5, 2022 · 3 comments
Open

关于 “1.5.3 顺序一致性内存模型”中的疑问 #604

JOJO0527 opened this issue Oct 5, 2022 · 3 comments

Comments

@JOJO0527
Copy link

JOJO0527 commented Oct 5, 2022

var a string
var done bool

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

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

但是 Go 语言并不保证在 main 函数中观测到的对 done 的写入操作发生在对字符串 a 的写入的操作之后,因此程序很可能打印一个空字符串。更糟糕的是,因为两个线程之间没有同步事件,setup线程对 done 的写入操作甚至无法被 main 线程看到,main函数有可能陷入死循环中。

我明白这里的顺序一致性内存模型的含义,如果来Java里面的知识做对比的话,应该就是volatile关键字的作用。但是我在Go1.18 arm中运行上述例子,无法重现main函数陷入死循环的情景,想请教下如果想验证的话,有什么实验可以验证呢?

@Engrtao
Copy link

Engrtao commented Nov 23, 2022

例子是错误的,全局变量顺序一致性肯定能保证的

@JOJO0527
Copy link
Author

例子是错误的,全局变量顺序一致性肯定能保证的

请问有相关资料可以说明吗

@cch123
Copy link
Collaborator

cch123 commented Feb 23, 2023

这个例子是官方的

死循环是理论结果,确实不好复现

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants