英文:
What is go's preferred way to synchronize goroutines
问题
我有一个昂贵的函数,我要在一个切片的所有项上应用这个函数。我正在使用goroutines来处理,每个goroutine处理一个切片项。
问题是,如注释所示,在调用someValue
函数之前,等待所有的goroutines完成工作的首选方法是什么?将一个通道传递给performSlow
函数,并等待每个goroutine在通道上写入后再继续执行可以工作,但似乎有点过度设计:
func Huge(lst []foo) {
ch := make(chan bool)
for _, item := range lst {
go performSlow(item, ch) // performSlow完成其工作,然后在ch上写入一个虚拟值
}
for i := range lst {
_ = <-ch
}
return someValue(lst)
}
有没有更好(更高效和/或更符合惯例)的方法来实现这个?
英文:
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 ?
答案1
得分: 12
使用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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论