[英]Need run a goroutine for WaitGroup in a function
我从https://go.dev/blog/pipelines阅读了一篇管道文章。
我试图删除覆盖wg.Wait()的 goroutine,但结果导致所有 goroutine 都处于睡眠状态 - 死锁!
我真的不明白为什么。
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
是一个阻塞通道。 您需要return out
并让一些东西从out
消耗,否则output
goroutines 将在尝试写入任何内容时立即阻塞。 如果在消费者甚至有机会开始之前merge
等待等待组(即等待一切完成),那是不可避免的死锁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.