关于并发的问题,这个例子要怎么理解?

The Go Memory Model

文章中有这么一段示例,该怎么理解?

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.

共 1 个回复


zweite

等待另外的goroutine初始化g

# 0