Wait Group Placement for Accurate Counting
In concurrent programming, the sync.WaitGroup type serves as a synchronization primitive for coordinating goroutines. It tracks the number of tasks that need to complete before a blocking call to wg.Wait() can proceed.
Proper Placement of wg.Add()
To ensure accurate task counting, it's crucial to call wg.Add(1) before launching a goroutine that subsequently calls wg.Done(). This placement guarantees that the main goroutine will block at wg.Wait() until all launched goroutines have completed.
Alternate Placement Consequences
As demonstrated in the example code, placing wg.Add(1) within the goroutine can lead to premature completion of wg.Wait(). This occurs because, within the same goroutine, wg.Done() is called immediately after wg.Add(1), causing the main goroutine to resume execution before all tasks are finished.
Deterministic Completion
When wg.Add() is correctly placed before the goroutine launches, the main goroutine cannot reach wg.Wait() until after the for loop. This ensures that wg.Add() is called exactly 100 times, and thus wg.Wait() blocks until wg.Done() is called 100 times.
Alternatives
As an alternative, if the number of loop iterations is known in advance, wg.Add(100) can be called before the loop. However, this approach should be used with caution, as it assumes no conditional skipping within the loop.
Best Practices
For consistent and reliable usage of sync.WaitGroup, follow these guidelines:
The above is the detailed content of Where Should You Place `wg.Add()` for Accurate Counting in Go\'s `sync.WaitGroup`?. For more information, please follow other related articles on the PHP Chinese website!