4 ms·
I prefer to call add once if I know how many routines I will create. var wg sync.WaitGroup n := 10 wg.Add(n) for i := 0; i < n; i++ { g
by shhsshs 7y ago
I prefer to call add once if I know how many routines I will create.
var wg sync.WaitGroup
n := 10
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
doSomething()
}()
}
wg.Wait()
You still have to call wg.Done(), unfortunately. People have written small wrappers around sync.WaitGroup that change the interface:
var wg bettersync.WaitGroup
n := 10
for i := 0; i < n; i++ {
wg.Go(func() {
doSomething()
})
}
wg.Wait()