Does WaitGroup.Wait() imply memory barrier in this case?

hon*_*jde 6 concurrency go

var condition bool
var wg sync.WaitGroup
for _, item := range items {
    wg.Add(1)
    go func(item) {
        if meetsCondition(item) {
            condition = true
        }
        wg.Done()
    }(item)
}
wg.Wait()
// is it safe to check condition here?
Run Code Online (Sandbox Code Playgroud)

There is a discussion of this question at the old go forum here: https://groups.google.com/forum/#!topic/golang-nuts/5oHzhzXCcmM The answer there was yes, it is safe. Then the discussion digress to use of atomic, etc., which is not what I want to ask about.

There is not even one mention of WaitGroup in the spec and it's documentation is saying WaitGroup.Wait: "Wait blocks until the WaitGroup counter is zero." which does not set any happens-before relationship (or does it?).

Does it mean that the first answer "It is safe to check condition after wg.Wait returns" is unofficial? If it's official what are the reasons for it I am missing? Thanks alot if you answer.

Update: This is update after @peterSO's @ravi's answers. Thanks.

Well, obviously there can be a race condition if you choose number of items > 1. Hint: condition can be set only to true. Still, I have the same question.

And probably, I should have stated that:

  1. underlying architectures can be only x86, x64 or ARM
  2. number of items can be 1

Update 2 I created followup question for the case when number of items == 1 here: Can you make this 'incorrectly synchronized' test fail?

Rav*_*i R 2

condition嗯,在之后进行检查是绝对安全的wg.Wait()但是您应该condition 使用互斥体进行保护,以避免它被多个 go 例程同时“写入”。这就是为什么 @peterSO 在他的代码第 20 行遇到了竞争条件 b'cos,该代码设置了多个 go 例程试图同时condition = true设置。condition这是一个包含 20k go 例程的示例https://play.golang.org/p/o3v6s_2qsY 。

作为我推荐的最佳实践,defer wg.Done()在 go 例程函数的开头添加,这样即使中间有 return 语句,wg.Done()仍然会被调用。