Synchronization 什么是围棋';s同步goroutine的首选方法
我有一个昂贵的函数,我适用于一个切片的所有项目。我使用goroutine来处理这个问题,每个goroutine处理一个片段Synchronization 什么是围棋';s同步goroutine的首选方法,synchronization,go,goroutine,Synchronization,Go,Goroutine,我有一个昂贵的函数,我适用于一个切片的所有项目。我使用goroutine来处理这个问题,每个goroutine处理一个片段 func Huge(lst []foo) { for _, item := range lst { go performSlow(item) } // How do I synchronize here ? return someValue(lst) } 问题是,如注释所示,在调用someValue函数之前,等待所有goroutine完成其工作
func Huge(lst []foo) {
for _, item := range lst {
go performSlow(item)
}
// How do I synchronize here ?
return someValue(lst)
}
问题是,如注释所示,在调用someValue
函数之前,等待所有goroutine完成其工作的首选方式是什么?将一个频道传递到performSlow
并等待每个人都写上它,这样做是可行的,但似乎有些过分:
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)
}
func巨型(lst[]foo){
ch:=制造(陈布尔)
对于u,项目:=范围lst{
go performSlow(item,ch)//performSlow执行其工作,然后向ch写入一个伪值
}
对于i:=范围lst{
_=使用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)
}