Go语言中同步goroutine的首选方式是什么?

huangapple go评论93阅读模式
英文:

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 {
     _ = &lt;-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)
}

huangapple
  • 本文由 发表于 2013年11月19日 02:07:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/20054671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定