let's say I want to start a group of goroutines and than wait for all of them to finish (e.g. return). I can think of some channel-based solution (e.g. create a channel and listen to it counting received messages which shall be sent by each of goroutines and quiting after receive corresponding number of msgs) but maybe there's a more elegant/efficient solution because this case seems very common.
Asked
Active
Viewed 2,997 times
3
-
2You're correct; it is a common problem. See: [`sync.WaitGroup`](https://godoc.org/sync#WaitGroup) – Dec 29 '15 at 19:18
1 Answers
6
Yes; you want a *sync.WaitGroup
, which you can use by calling waitGroup.Add(1)
before starting each task, waitGroup.Done()
when it finishes, and waitGroup.Wait()
once you have started everything and want to wait for it all to finish, like this:
package main
import (
"fmt"
"sync"
"time"
)
func main() {
wg := new(sync.WaitGroup)
for i := 1; i < 3; i++ {
wg.Add(1)
go func(i int) { // ensures each run gets distinct i
fmt.Println("Sleeping", i, "seconds")
time.Sleep(time.Duration(i) * time.Second)
fmt.Println("Slept", i, "seconds")
wg.Done()
}(i)
}
wg.Wait()
fmt.Println("All done")
}

twotwotwo
- 28,310
- 8
- 69
- 56