Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Synchronization 什么是围棋';s同步goroutine的首选方法_Synchronization_Go_Goroutine - Fatal编程技术网

Synchronization 什么是围棋';s同步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完成其工作

我有一个昂贵的函数,我适用于一个切片的所有项目。我使用goroutine来处理这个问题,每个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)
}