且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

抛出:所有的goroutines都睡着了 - 僵局

更新时间:2023-11-21 19:16:28

你不会关闭 ch 频道,因此范围循环永远不会结束。不能在同一个频道上发回结果。一个解决方案是使用不同的解决方案。

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