Go WaitGroup with goroutine

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

Go WaitGroup with goroutine

问题

我想知道为什么我们需要在goroutine中运行wg.Wait()

// 这个例子按预期工作...
func main() {
var wg sync.WaitGroup
for i:=0; i<5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
}()
time.Sleep(time.Second)
}
go func() {
wg.Wait()
}()
}

但是这个例子永远不会结束等待。

func main() {
var wg sync.WaitGroup
for i:=0; i<5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
}()
time.Sleep(time.Second)
}
wg.Wait()
}

有人能解释一下为什么我需要在另一个goroutine中等待吗?

谢谢!

英文:

I wonder why we need to run the wg.Wait() in goroutine

  1. // This one works as expected...
  2. func main() {
  3. var wg sync.WaitGroup
  4. for i:=0; i&lt;5; i++ {
  5. wg.Add(1)
  6. go func() {
  7. defer wg.Done()
  8. }()
  9. time.Sleep(time.Second)
  10. }
  11. go func() {
  12. wg.Wait()
  13. }()
  14. }

But this one never ends waiting forever

  1. func main() {
  2. var wg sync.WaitGroup
  3. for i:=0; i&lt;5; i++ {
  4. wg.Add(1)
  5. go func() {
  6. defer wg.Done()
  7. }()
  8. time.Sleep(time.Second)
  9. }
  10. wg.Wait()
  11. }

Can anybody explain why I need to wait in another goroutine?

Thanks!

答案1

得分: 1

为什么我们需要在goroutine中运行wg.Wait()

在你提到的例子中(coop/blob/master/coop.go#L85),在goroutine中运行等待是为了立即返回一个通道,该通道将指示所有其他goroutine何时完成。
以下是要启动的goroutine:

  1. for _, fn := range fns {
  2. go func(f func()) {
  3. f()
  4. wg.Done()
  5. }(fn)
  6. }

它们通过var wg sync.WaitGroup来指示完成。
该WaitGroup设置为等待正确数量的goroutine完成:

  1. wg.Add(len(fns))

等待是在goroutine中完成的,因为它将向全局完成通道发出信号:

  1. go func() {
  2. wg.Wait()
  3. doneSig(ch, true)
  4. }()

但是通道会立即返回。

  1. ch := make(chan bool, 1)
  2. ...
  3. return ch

这就是为什么等待是异步完成的原因:你不想在这个函数中等待。你只想要通道。

英文:

> why we need to run the wg.Wait() in goroutine?

In the example you mention (coop/blob/master/coop.go#L85), the wait is in a goroutine in order to return immediately a channel that will indicate when all the other goroutines have completed.
Those are the goroutines to be started:

  1. for _, fn := range fns {
  2. go func(f func()) {
  3. f()
  4. wg.Done()
  5. }(fn)
  6. }

They mention the completion through the var wg sync.WaitGroup.
That WaitGroup is set to wait for the right number of goroutines to finish:

  1. wg.Add(len(fns))

The wait is done in a goroutine because it will in turn signal the global completion to a channel:

  1. go func() {
  2. wg.Wait()
  3. doneSig(ch, true)
  4. }()

But the channel is returned immediately.

  1. ch := make(chan bool, 1)
  2. ...
  3. return ch

That is why the Wait is done asynchronously: you don't want to wait in this function. You just want the channel.

huangapple
  • 本文由 发表于 2014年12月4日 15:24:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/27288399.html
匿名

发表评论

匿名网友

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

确定