You're supposed to do Add(1) -> Wait; and you'd normally wait once, in a 
single goroutine. Typical pattern:

wg.Add(1)
go func() {
    defer wg.Done()
    ... foo
}
wg.Add(1)
go func() {
    defer wg.Done()
    ... bar
}
wg.Wait()  // wait for both goroutines to complete

On Tuesday, 17 January 2023 at 04:56:44 UTC bodqh...@gmail.com wrote:
The goroutine has a Wait -> Add(1) -> Done chain.

*Inside* a goroutine? That sounds problematic and racy, as you've found.

- you're Waiting on the same waitgroup in multiple goroutines 
concurrently?  Then when it counts to zero, multiple goroutines would be 
able to start to run

- you're  re-adding to a waitgroup even after it's counted down to zero?  
That means that "wait" is non-deterministic (it may miss a count down to 
zero and back up again).

It sounds to me like you need some other synchronization primitive, but I 
don't know what it is you're trying to do.  Possibly a semaphore.

This video is well worth watching, several times:
https://www.youtube.com/watch?v=5zXAHh5tJqQ

This opened my eyes to a very useful pattern:
- have a one-item buffered channel
- push a value into that channel
- whenever you want to use it: pop it out, use it, and push the updated 
value back in

This is a very simple and clean way of doing what would otherwise require a 
mutex to protect.

Maybe also useful:
https://www.youtube.com/watch?v=f6kdp27TYZs
https://www.youtube.com/watch?v=oV9rvDllKEg

-- 
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 golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/475d96a1-c628-42bd-9fcd-62fe66277599n%40googlegroups.com.

Reply via email to