5

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.

0

1 Answer 1

11

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.

7
  • the "add" go-routine creates the "done" go-routine and I can just add(1) at startup (and then have my "stop" function call an extra done then call wait), so looks like I'll be fine. Thanks! I'll accept in a couple minutes.
    – Bren
    Dec 13, 2018 at 20:09
  • That's one way to do it, but less clear than the recommended style used in the example in the docs.
    – Adrian
    Dec 13, 2018 at 20:12
  • Well it using a the httpserver which creates a new routine per request. I suppose this where channels could be used
    – Bren
    Dec 13, 2018 at 20:13
  • This seems like a very irregular design and worthy of some additional thought. Graceful shutdown of a server is not a simple matter of applying a WaitGroup, and a channel definitely isn't going to help. You likely don't want to call Wait at all until a shutdown has been requested, in which case you can call Add and Done both in the handler routine, and call Wait after you've stopped your Listener.
    – Adrian
    Dec 13, 2018 at 20:16
  • yes, the add(1) is not required as wait is not called until after the httpserver stops. My stop function closes the server then the handler. The running server keeping the program from preternaturally exiting was the part I was missing. Thanks again!
    – Bren
    Dec 13, 2018 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.