On 26 April 2018 at 16:29, Jon Bodner <[email protected]> wrote:
> Hello,
>
> We were having a discussion at work about passing around references to
> sync.WaitGroup. I said it was a bad idea, because if a goroutine launched a
> goroutine of its own and called sync.WaitGroup.Add() after a goroutine
> called sync.WaitGroup.Wait(), but before the count dropped to 0, your code
> would panic. The comments seem to support this:
>
> "If a WaitGroup is reused to wait for several independent sets of events,
> new Add calls must happen after all previous Wait calls have returned."
>
> And the WaitGroup source code for Add has lines like this:
>
> if w != 0 && delta > 0 && v == int32(delta) {
> panic("sync: WaitGroup misuse: Add called concurrently with Wait")
> }
>
> But a co-worker wrote this code, and it runs without a panic:
> https://play.golang.org/p/NjqK_YoqHeH

FWIW This code is fine, and was part of the original design goal of
WaitGroup. When the count is known to be non-zero (for example because
the current goroutine has previously done an Add) it's OK to call Add
to add more.

The key in the above quote is "If a WaitGroup is reused to wait for
several independent sets of events". If you're reusing a WaitGroup,
this makes sense, but in the example above, the WaitGroup is not
reused so all is good.

As for the panic, others have already explained how that might happen.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to