Reputation: 13406
I have an expensive function that I apply on all items of a slice. I'm using goroutines to deal with that, each goroutine dealing with one item of the slice.
func Huge(lst []foo) {
for _, item := range lst {
go performSlow(item)
}
// How do I synchronize here ?
return someValue(lst)
}
The question is, as shown in the comment, what is the preferred way to wait all goroutines have done their job before calling the someValue
function ? Passing on a channel to performSlow
and waiting until everyone has written on it works, but it seems overkill :
func Huge(lst []foo) {
ch := make(chan bool)
for _, item := range lst {
go performSlow(item, ch) // performSlow does its job, then writes a dummy value to ch
}
for i := range lst {
_ = <-ch
}
return someValue(lst)
}
Is there a better (i.e. more efficient and/or more idiomatic) way to do it ?
Upvotes: 6
Views: 1221
Reputation: 16100
Use sync.WaitGroup (http://godoc.org/sync#WaitGroup)
func Huge(lst []foo) {
var wg sync.WaitGroup
for _, item := range lst {
wg.Add(1)
go func() {
performSlow(item)
wg.Done()
}()
}
wg.Wait()
return someValue(lst)
}
Upvotes: 12