【问题标题】:What is go's preferred way to synchronize goroutinesgo 同步 goroutine 的首选方式是什么
【发布时间】:2013-11-18 18:07:18
【问题描述】:

我有一个昂贵的功能,我将其应用于切片的所有项目。我正在使用 goroutines 来处理这个问题,每个 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)
}

有没有更好(即更有效和/或更惯用)的方法来做到这一点?

【问题讨论】:

    标签: synchronization go goroutine


    【解决方案1】:

    使用 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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 2014-11-03
      • 2014-09-16
      • 1970-01-01
      • 2012-11-27
      相关资源
      最近更新 更多