登录
首页 >  Golang >  Go问答

Goroutines 引发了死锁

来源:stackoverflow

时间:2024-03-14 22:27:28 236浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《Goroutines 引发了死锁》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我正在尝试 goroutine,并提出了这个示例 - https://go.dev/play/p/mWHUmALk-1_K

但是我遇到了这个错误 - fatal 错误:所有 goroutine 都在睡觉 - 死锁!

我已尝试解决此问题,但没有成功。请问我该如何解决这个问题?

错误似乎出现在第 15、23 和 32 行。


正确答案


问题是你的程序启动了 3 个独立的 goroutine,它们发送到同一个通道。并且主协程只能从该通道接收一次。这会导致第二个通道发送 (ch <- fmt.sprintf("...) 无限期地阻塞。使用无缓冲通道,您需要执行与发送一样多的接收操作。

确保接收所有发送的一种方法是在通道上使用 range 循环。

func getLength(dd []string, wg *sync.WaitGroup) {
    wg.Add(len(dd))
    c := make(chan string)
    for _, d := range dd {
        d1 := d
        go computeLength(d1, c, wg)
    }

    // close c once all goroutines are done to
    // ensure the for-range loop below exits.
    go func() { wg.Wait(); close(c) }()

    // Use for-range loop on the channel to receive all the sends.
    //
    // But note that a for-range loop over a channel exits only
    // when the channel is closed or the loop is exited from within.
    //
    // So to exit you can close c once wg.Wait() returns,
    // that's why there's that extra goroutine above.
    for v := range c {
        fmt.Println(v)
    }
}

https://go.dev/play/p/BUb7NHrq2B0

本篇关于《Goroutines 引发了死锁》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>