执行闭包goroutine未能达到预期结果

Executing a closure goroutine fails to achieve the expected result

func main() {
    var number int = 0
    go func() {
        for {
            number++
            //time.Sleep(time.Nanosecond)
        }
    }()
    for {
        fmt.Println(number)
        time.Sleep(time.Second)
    }
}

number的打印一直是0,但是在for循环中加入了time.Sleep(time.Nanosecond)语句后,打印的值就正常了。为什么?

您有一场数据竞赛。阅读 Go 内存模型:

https://golang.org/ref/mem

如果 goroutine 之间没有使用通道或锁的显式同步,那么就没有 happened-before 关系,也不能保证一个 goroutine 会看到另一个 goroutine 的效果。如果您使用的是 Go v1.13 或更早版本,那么繁忙循环将不会屈服于其他 goroutines。