Sobes.tech
Intern

What happens if the sync.WaitGroup counter becomes negative due to excess calls to Done compared to Add?

sobes.tech AI

Answer from AI

If the counter of sync.WaitGroup in Go becomes negative due to more calls to Done() than Add(), a panic will occur at runtime.

WaitGroup tracks the number of goroutines to wait for through a counter. When calling Add(n), the counter increases by n, and when calling Done() — decreases by 1. If the counter becomes less than zero, it is considered a usage error.

Example of an error:

var wg sync.WaitGroup
wg.Add(1)
wg.Done()
wg.Done() // extra call, will cause panic

The panic occurs with the message:

panic: sync: negative WaitGroup counter

Therefore, it is important to strictly maintain the balance between Add and Done to avoid this error.

What happens if the sync.WaitGroup counter becomes… - sobes.tech