给定以下简单的围棋程序

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!

谢谢

推荐答案

由于您永远不会关闭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)
}

Go相关问答推荐

允许在 struct 中使用复合作为函数参数

如何修复proxyconnect tcp:tls:第一条记录看起来不像tls握手

如何修复 Go 中协议缓冲区定义中重新定义的字段?

`docker system df` 与 `/system/df` (docker api 端点)

Go 中的 protobuf FieldMask 解组

使用Dockertest进行Golang SQL单元测试的基本设置

最长连续重复的字符golang

如何使用 sync.WaitGroup 来执行所有的 goroutine?

我的神经网络(从头开始)训练,让它离目标更远

如何判断范围内的字段?

是否可以从 golang 中的参数推断类型?

Golang代码判断第一个词是否可以从第二个词形成

golang 中的可变参数函数

Golang Oauth2 服务帐户返回空刷新令牌字符串

此代码如何生成内存对齐切片?

当有多个同名包时如何在vscode中显示golang包完整路径?

如何使用带有Electron 表格 ID、Electron 表格名称、表格 ID 和值的 golang 在 googlesheet 中插入数据

如何在 Unmarshal 中使用泛型(转到 1.18)

在 VSCode 中使用命令行参数调试 Go 测试

try 创建新的 etcdv3 客户端时出现pc error: code = Unavailable desc = error reading from server: EOF