Junior — Middle
What is the difference between using wg.Add inside a loop and before the loop in the context of synchronization in Go?
sobes.tech AI
Answer from AI
In Go, wg.Add increments the WaitGroup counter. The difference between calling wg.Add inside a loop and before the loop:
- Calling
wg.Addbefore the loop: the counter is increased once for the total number of goroutines that will be launched. This is safe and recommended, as the counter is set beforehand.
wg.Add(3) // increase the counter beforehand
for i := 0; i < 3; i++ {
go func() {
defer wg.Done()
// work
}()
}
wg.Wait()
- Calling
wg.Addinside the loop: the counter is increased in each iteration, which also works but can lead to race conditions if goroutines are launched asynchronously and callDonebeforeAddhas been called for all.
for i := 0; i < 3; i++ {
wg.Add(1) // increase the counter in the loop
go func() {
defer wg.Done()
// work
}()
}
wg.Wait()
Recommendation: it is better to call wg.Add before launching goroutines to avoid potential synchronization issues.