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

Getting Goroutine deadlock when using for loop to traverse through the channel

我正在尝试练习 goroutine 和通道,我在调用 goroutine 和传递通道时遇到问题。 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()
}

不确定你的问题是什么,但我会告诉你会发生什么。你的两侧 goroutines 将它们的数字推送到通道并退出。然后主 goroutine(此时唯一剩下的)将永远阻塞,等待另一个元素从通道中出来。

当 goroutines 完成后,关闭通道以指示不会添加更多值。收到所有值后,for 循环将中断。

c := make(chan int)
var w sync.WaitGroup
w.Add(2)
go smallThread(1, c, &w)
go smallThread(2, c, &w)
go func() {
    w.Wait()
    close(c)
}()

for i := range c {
    fmt.Println(i)
}