doumi9618 2017-02-09 22:58
浏览 217
已采纳

for循环导致死锁

I have written some code example from GO Concurrency :

func gen(numbers ...int) <-chan int {
    out := make(chan int)

    go func() {
        for _, number := range numbers {
            out <- number
        }
        close(out)
    }()

    return out
}

func sq(in <-chan int) <-chan int {
    out := make(chan int)

    go func() {
        for number := range in {
            out <- number * number
        }
    }()

    return out
}

so I tried to use above code in my main function like this :

func main() {



    result := sq(sq(sq(gen(1, 2, 3, 4))))

    fmt.Println(<-result)
    fmt.Println(<-result)
    fmt.Println(<-result)
    fmt.Println(<-result)

    fmt.Println("-------------------")

    for channelValue := range sq(sq(sq(gen(1, 2, 3, 4)))) {
        fmt.Println(channelValue)
    }

}

I was confused when I run the code I got this message after the loop:

fatal error: all goroutines are asleep - deadlock

Please help me to understand this. From what I understand is calling the fmt.Prinlnt(result) x 4 times is the same as the for loop on for channelValue := range sq(sq(sq(gen(1, 2, 3, 4)))). is this correct?

Could please tell me why I got deadlock after the loop?

  • 写回答

2条回答 默认 最新

  • douchuoliu4422 2017-02-09 23:16
    关注

    The range over the channel blocks because the channel is not closed in sq.

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

    A good way to debug deadlocks like this is to send the process a SIGQUIT. The runtime dumps the stacks of all the goroutines when a SIGQUIT is received. The stack dumps will often point to the issue.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?