抛出:所有的goroutines都睡着了 - 僵局 [英] throw: all goroutines are asleep - deadlock

查看:142
本文介绍了抛出:所有的goroutines都睡着了 - 僵局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下简单的Go程序

Given the following simple Go program

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

我想知道是否有人可以启发我为什么得到

I am wondering if someone can enlighten me as to why I get

throw: all goroutines are asleep - deadlock!

谢谢

thank you

推荐答案

你不会关闭 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)
}

这篇关于抛出:所有的goroutines都睡着了 - 僵局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆