Sobes.tech
Intern

Mis juhtub, kui sync.WaitGroup loendur muutub negatiivseks, kuna Done kutsed on rohkem kui Add?

sobes.tech AI

Vastus AI-lt

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

WaitGroup tracks the number of expected goroutines using a counter. When calling Add(n), the counter increases by n, and with 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 a balance between Add and Done to avoid this error.