[英]Need run a goroutine for WaitGroup in a function
I've read a pipeline article from https://go.dev/blog/pipelines .我从https://go.dev/blog/pipelines阅读了一篇管道文章。
I've tried to remove the goroutine that covers wg.Wait() but it turns out that caused all goroutines are asleep - deadlock!我试图删除覆盖wg.Wait()的 goroutine,但结果导致所有 goroutine 都处于睡眠状态 - 死锁!
I really don't understand why.我真的不明白为什么。
func merge(cs ...<-chan int) <-chan int {
var wg sync.WaitGroup
out := make(chan int)
// Start an output goroutine for each input channel in cs. output
// copies values from c to out until c is closed, then calls wg.Done.
output := func(c <-chan int) {
for n := range c {
out <- n
}
wg.Done()
}
wg.Add(len(cs))
for _, c := range cs {
go output(c)
}
// Start a goroutine to close out once all the output goroutines are
// done. This must start after the wg.Add call.
go func() {
wg.Wait()
close(out)
}()
return out
}
out
is a blocking channel. out
是一个阻塞通道。 You need to return out
and let something consume from out
, or else the output
goroutines will block as soon as they try to write anything.您需要
return out
并让一些东西从out
消耗,否则output
goroutines 将在尝试写入任何内容时立即阻塞。 If merge
waits on the waitgroup (ie waits for everything to finish) before the consumer even has a chance to start , that's an inevitable deadlock.如果在消费者甚至有机会开始之前
merge
等待等待组(即等待一切完成),那是不可避免的死锁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.