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?
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:
- underlying architectures can be only x86, x64 or ARM
- 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?