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.
1 Answer
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.
-
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.– BrenDec 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.– AdrianDec 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– BrenDec 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 callAdd
andDone
both in the handler routine, and callWait
after you've stopped yourListener
.– AdrianDec 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!– BrenDec 13, 2018 at 20:32