小编典典

抛出:所有goroutine都在睡眠中-死锁

go

给出以下简单的Go程序

package main

import (
    "fmt"
)

func total(ch chan int) {
    res := 0
    for iter := range ch {
        res += iter
    }
    ch <- res
}

func main() {
    ch := make(chan int)
    go total(ch)
    ch <- 1
    ch <- 2
    ch <- 3
    fmt.Println("Total is ", <-ch)
}

我想知道是否有人可以启发我

throw: all goroutines are asleep - deadlock!

谢谢


阅读 212

收藏
2020-07-02

共1个答案

小编典典

由于您从不关闭ch通道,因此范围循环将永远不会结束。

您不能在同一频道上发送结果。一种解决方案是使用其他解决方案。

您的程序可以这样修改:

package main

import (
    "fmt"
)

func total(in chan int, out chan int) {
    res := 0
    for iter := range in {
        res += iter
    }
    out <- res // sends back the result
}

func main() {
    ch := make(chan int)
    rch  := make(chan int)
    go total(ch, rch)
    ch <- 1
    ch <- 2
    ch <- 3
    close (ch) // this will end the loop in the total function
    result := <- rch // waits for total to give the result
    fmt.Println("Total is ", result)
}
2020-07-02