Sobes.tech
Junior — Middle

What are the consequences if the number of calls to wg.Add does not match the number of goroutines launched?

sobes.tech AI

Answer from AI

In Go, sync.WaitGroup is used to wait for a collection of goroutines to finish. The method wg.Add(n) increments the counter by n, and wg.Done() decrements it by 1. If the number of calls to wg.Add does not match the number of goroutines started (i.e., calls to wg.Done), then:

  • If wg.Add is less than the number of wg.Done calls, the counter may become negative when wg.Done is called, leading to a runtime panic.
  • If wg.Add is greater than the number of wg.Done calls, the call to wg.Wait() will block forever, as the counter will never reach zero — leading to a deadlock.

Therefore, it is important to call wg.Add with the correct number before starting goroutines and to call wg.Done exactly as many times as wg.Add was called.

What are the consequences if the number of calls to… - sobes.tech