throw: all goroutines are asleep - deadlock

点点圈 提交于 2019-11-27 08:51:57

As you never close the ch channel, the range loop will never finish.

You can't send back the result on the same channel. A solution is to use a different one.

Your program could be adapted like this :

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)
}

This is also right.

package main

import "fmt"

func main() {
    c := make(chan int)
    go do(c)
    c <- 1
    c <- 2
    // close(c)
    fmt.Println("Total is ", <-c)
}

func do(c chan int) {
    res := 0
    // for v := range c {
    //  res = res + v
    // }
    for i := 0; i < 2; i++ {
        res += <-c
    }
    c <- res
    fmt.Println("something")
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!