go - 使用for循环遍历 channel 时出现Goroutine死锁

标签 go channel goroutine

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

我已经使用 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)
    }
}

编辑: 使用 WaitGroup :

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 完成后,关闭 channel 以指示不会添加更多值。收到所有值后,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)
}

关于go - 使用for循环遍历 channel 时出现Goroutine死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56743291/

相关文章:

go - 链式函数如何作为 goroutines 执行?

json - 当结构未知时遍历 JSON 响应

arrays - 我在 golang 中使用 make 方法创建二维数组时遇到问题 "panic: runtime error: index out of range"

python - Django Websockets 数据转到错误的套接字

multithreading - Golang 中的 channel 和 mutex 有什么区别?

go - 为什么 goroutines 比其他语言的线程便宜很多?

json - 您如何在Go中阅读嵌套的Json?

inheritance - 使用嵌入式接口(interface)字段在 Go 中正确实现继承

arrays - 重构代码以惯用方式使用单个 channel

go - 为什么在使用 select 并顺序将值输入 2 个 channel 时所有 goroutine 都处于休眠状态?