猿问

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

给出以下简单的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!

谢谢你


DIEA
浏览 163回答 2
2回答

森栏

由于您从不关闭ch通道,因此范围循环将永远不会结束。您无法在同一频道上发送结果。一种解决方案是使用不同的解决方案。您的程序可以像这样进行修改:package mainimport (&nbsp; &nbsp; "fmt")func total(in chan int, out chan int) {&nbsp; &nbsp; res := 0&nbsp; &nbsp; for iter := range in {&nbsp; &nbsp; &nbsp; &nbsp; res += iter&nbsp; &nbsp; }&nbsp; &nbsp; out <- res // sends back the result}func main() {&nbsp; &nbsp; ch := make(chan int)&nbsp; &nbsp; rch&nbsp; := make(chan int)&nbsp; &nbsp; go total(ch, rch)&nbsp; &nbsp; ch <- 1&nbsp; &nbsp; ch <- 2&nbsp; &nbsp; ch <- 3&nbsp; &nbsp; close (ch) // this will end the loop in the total function&nbsp; &nbsp; result := <- rch // waits for total to give the result&nbsp; &nbsp; fmt.Println("Total is ", result)}
随时随地看视频慕课网APP

相关分类

Go
我要回答