WaitGroup 数据同步保证

WaitGroup data sync guarantees

Go memory model,说明如下:

Programs that modify data being simultaneously accessed by multiple goroutines must serialize such access. To serialize access, protect the data with channel operations or other synchronization primitives such as those in the sync and sync/atomic packages.

遗憾的是,文档没有具体说明 synchronization primitive 它们涉及什么。

我的问题是,WaitGroup 是否包含在那些 synchronization primitives 中?

根据上面的说法,在下面的代码中,done可能永远不会被看作是真的:

var a string
var done bool

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

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

WaitGroup 是否保证一旦 waitgroup.Wait() 被调用,在组的 goroutines 执行中写入共享内存的值将被视为最新值?

换句话说,下面的代码能保证打印出“hello”吗? (Playground)

package main

import (
    "sync"
)

var a string = "start"
var wg sync.WaitGroup

func hello() {
    wg.Add(1)
    go func() { 
        a = "hello" 
        wg.Done()
    }()
    wg.Wait()
    print(a)
}

func main() {
    hello()
}

您的问题的答案都是:WaitGroup 是一个同步原语,这就是它在 sync 包中的原因。对 Wait() 的调用保证您将看到 a 的正确值。代码保证打印“hello”。

没什么好说的了。