使用for循环遍历通道时出现Goroutine死锁

我正在尝试练习 goroutine 和通道,但我遇到了调用 gorouting 和传递通道的问题。Goroutine 将数据推送到通道中,然后主线程将打印元素。


我已经使用 for 循环来打印内容但是得到了。


fatal error: all goroutines are asleep - deadlock!


2

1

goroutine 1 [chan receive]:

main.main()

package main


import "fmt"



func smallThread(a int, c chan int) {

    c <- a

}


func main() {

    c := make(chan int)

    go smallThread(1, c)

    go smallThread(2, c)

    for {

        fmt.Println(<-c)

    }

}


编辑:使用等待组:


func smallThread(a int, c chan int, w *sync.WaitGroup) {

    c <- a

    w.Done()

}


func main() {

    c := make(chan int)

    var w sync.WaitGroup

    w.Add(2)

    go smallThread(1, c, &w)

    go smallThread(2, c, &w)

    //w.Wait()

    for i := range c {

        fmt.Println(i)

    }

    w.Wait()

}

EDIT2:工作代码


func smallThread(a int, c chan int, w *sync.WaitGroup) {

    //defer w.Done()

    c <- a

    w.Done()

}


func main() {

    c := make(chan int)

    var w sync.WaitGroup

    w.Add(1)

    go smallThread(1, c, &w)

    w.Add(1)

    go smallThread(2, c, &w)

    go func(c chan int) {

        for i := range c {

            fmt.Println(i)

        }

    }(c)

    w.Wait()

}


慕尼黑的夜晚无繁华
浏览 106回答 2
2回答

慕莱坞森

当 goroutine 完成后,关闭通道以指示不再添加任何值。当接收到所有值后,for 循环将中断。c := make(chan int)var w sync.WaitGroupw.Add(2)go smallThread(1, c, &w)go smallThread(2, c, &w)go func() {&nbsp; &nbsp; w.Wait()&nbsp; &nbsp; close(c)}()for i := range c {&nbsp; &nbsp; fmt.Println(i)}

DIEA

不确定你的问题是什么,但我会告诉你会发生什么。你的两侧 goroutine 将它们的数字推送到通道并退出。然后主 goroutine(此时只剩下唯一的一个)将永远阻塞,等待另一个元素从通道中出来。
打开App,查看更多内容
随时随地看视频慕课网APP