douhu8851 2014-10-04 04:03
浏览 28
已采纳

以下golang代码死锁。 有人可以帮助理解为什么吗?

This example is taken from http://blog.golang.org/pipelines. It runs and gives correct answer but it shows following runtime error: "fatal error: all goroutines are asleep - deadlock!". Could anyone help me understand why this is happening? package main

import (
    "fmt"
)

func gen(nums ...int) <- chan int {
    out := make(chan int)
    go func() {
        for _, n := range nums {
            out <- n
        }
    }()
    return out
}

func sq(in <- chan int) <- chan int {
    out := make(chan int)
    go func() {
        for n := range in {
            out <- n * n
        }
        close(out)
    }()
    return out
}

func main() {
    for n := range sq(gen(2,3)) {
        fmt.Println(n)
    }
}

However the following modification doesn't.

func main() {
    // Set up the pipeline.
    c := gen(2, 3)
    out := sq(c)

    // Consume the output.
    fmt.Println(<-out) // 4
    fmt.Println(<-out) // 9
}
  • 写回答

1条回答 默认 最新

  • dpwu16132 2014-10-04 04:12
    关注

    The for n := range in of the sq() function never exits, and start blocking (after reading 2 values), because gen() never closed its channel.
    Adding close(out) to the go func of gen() would make it work: see playground.

    With channel, the receiver blocks until receiving a value.
    The range keyword, when used with a channel, will wait on the channel until it is closed.

    sq() is blocked, which means close(out) is never called, and in turn main() blocks on range sq() (since the channel sq isn't closed).

    In your second example, main() itself exits, which means even though sq() is blocked, everything still stops.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab