On Thu, Apr 26, 2018 at 8:29 AM, Jon Bodner <[email protected]> wrote:
>
> 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
>
> I thought that this code might only be working because the playground is
> single-threaded, but when this code is run locally, it also completes
> without panics. Running it with the race flag also works properly.
>
> How do you trigger those panics in the WaitGroup codebase?
Here's one panic:
package main
import (
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
time.Sleep(time.Millisecond)
wg.Add(-1)
wg.Add(1)
}()
wg.Wait()
}
Ian
--
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.