### The Go Memory Model
文章结尾有这么一段代码,理解的不是很透彻,谁给讲解一下,谢谢!
There are subtler variants on this theme, such as this program.
```
type T struct {
msg string
}
var g *T
func setup() {
t := new(T)
t.msg = "hello, world"
g = t
}
func main() {
go setup()
for g == nil {
}
print(g.msg)
}
```
Even if main observes g != nil and exits its loop, there is no guarantee that it will observe the initialized value for g.msg.
In all these examples, the solution is the same: use explicit synchronization.
Within a single goroutine, reads and writes must behave as if they executed in the order specified by the program. That is, compilers and processors may reorder the reads and writes executed within a single goroutine only when the reordering does not change the behavior within that goroutine as defined by the language specification. Because of this reordering, the execution order observed by one goroutine may differ from the order perceived by another. For example, if one goroutine executes a = 1; b = 2;, another might observe the updated value of b before the updated value of a.
func setup() {
t := new(T)
t.msg = "hello, world"
g = t
}
go setup()的实际执行顺序可能是:
func setup() {
t := new(T)
g = t
t.msg = "hello, world"
}
因为针对上面的例子,这样调换执行顺序并不违背明确的语法规则,要做同步就必须使用go的明确的语法规则,而不是上面的潜规则
#8