I am just starting learning golang, when reading Go Memory Model I got a question to understand what it says about "Another incorrect idiom is busy waiting for a value,"
var a string
var done bool
func setup() {
a = "hello, world"
done = true
}
func main() {
go setup()
for !done {
}
print(a)
}
It says:
"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."
I know that the order of writes to 'a' and 'done' is not deterministic in setup(), My question is: why main is not guaranteed to see the write to done?
Thank you
package main
var a string
var done bool
func setup() {
a = "hello, world"
done = true
}
func main() {
go setup()
for !done {
}
println(a)
}
You have two goroutines, main and setup. For example, assume that they are running on separate threads on separate CPUs with local memory cache. Assume that both main and setup read the done variable into a local CPU memory cache. The setup goroutine updates done in its local memory cache, which does lazy writes. Since there is no cache synchronization event between the independent main and setup goroutines there is no guarantee of cache coherency, no guarantee that main memory and both CPU memory caches will be synchronized. Different hardware handles this differently. In Go, only the lowest common denominator can be guaranteed.
See Cache coherence.