Does WaitGroup.Wait() Guarantee Memory Barrier?
Consider the following code snippet:
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?
The question arises whether it is safe to check the condition variable after wg.Wait() returns. The official Go documentation does not explicitly mention any memory barrier implications, but the WaitGroup documentation states that Wait blocks until the wait group counter reaches zero.
Solution
Yes, it is safe to check the condition variable after wg.Wait() returns. There is an implicit happens-before relationship between wg.Wait() and wg.Done(). When a goroutine calls wg.Done(), it ensures that all of its completed operations become visible to other goroutines that have already called wg.Wait(). Therefore, wg.Wait() effectively acts as a memory barrier, ensuring that the condition variable is updated before the check after wg.Wait() returns.
This happens-before relationship is not explicitly documented but has been confirmed by Go developers. Refer to the Go forum thread here for more details.
The above is the detailed content of Does WaitGroup.Wait() Act as a Memory Barrier in Go?. For more information, please follow other related articles on the PHP Chinese website!