Bren
Bren

Reputation: 3706

Is it safe to add to a waitgroup from multiple goroutines?

If I have multiple go routines concurrently adding and calling done to a waitgroup. Is this safe from a concurrency perspective? Most waitgroup examples I've seen keep the adding in a single go-routine that calls/creates the others.

Upvotes: 6

Views: 6094

Answers (1)

Adrian
Adrian

Reputation: 46602

Calling Done from multiple routines is safe and is the recommended usage of WaitGroup per the documentation. The reason to call Add from the goroutine that spawns more routines is not because Add is not thread-safe, it is because of the possibility that code like this:

for ... {
    go func() {
        wg.Add(1)
        defer wg.Done()
        ...
    }()
}
wg.Wait()

May get to the wg.Wait() before any of the calls to Add are executed, when the counter is still at zero, thereby defeating the purpose. The execution order of concurrent code is non-deterministic.

Upvotes: 19

Related Questions