英文:
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
// This one works as expected...
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()
}()
}
But this one never ends waiting forever
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()
}
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:
for _, fn := range fns {
go func(f func()) {
f()
wg.Done()
}(fn)
}
它们通过var wg sync.WaitGroup
来指示完成。
该WaitGroup设置为等待正确数量的goroutine完成:
wg.Add(len(fns))
等待是在goroutine中完成的,因为它将向全局完成通道发出信号:
go func() {
wg.Wait()
doneSig(ch, true)
}()
但是通道会立即返回。
ch := make(chan bool, 1)
...
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:
for _, fn := range fns {
go func(f func()) {
f()
wg.Done()
}(fn)
}
They mention the completion through the var wg sync.WaitGroup
.
That WaitGroup is set to wait for the right number of goroutines to finish:
wg.Add(len(fns))
The wait is done in a goroutine because it will in turn signal the global completion to a channel:
go func() {
wg.Wait()
doneSig(ch, true)
}()
But the channel is returned immediately.
ch := make(chan bool, 1)
...
return ch
That is why the Wait is done asynchronously: you don't want to wait in this function. You just want the channel.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论