繁体   English   中英

需要在 function 中为 WaitGroup 运行一个 goroutine

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM