douba4824 2016-07-02 10:43
浏览 90
已采纳

为什么该Go程序挂起?

I'm setting up a chain of three goroutines, each with an input an output channel. The goroutines will read from the input channel until it's closed, increment the value, send it to the output channel. However, the program below deadlocks with this output:

goroutine 'one': 1
goroutine 'two': 2
goroutine 'three': 3
goroutine 'one': 10
goroutine 'two': 11
goroutine 'one': 100
fatal error: all goroutines are asleep - deadlock!

Code:

package main

import (
  "fmt"
)

func int_channel(id string, i chan int, o chan int) {
  defer close(o)

  for x := range i {
    fmt.Printf("goroutine '%s': %d
", id, x)
    o <- x + 1
  }

  fmt.Println("done")
}

func main() {
  c0 := make(chan int)
  c1 := make(chan int)
  c2 := make(chan int)
  c3 := make(chan int)

  go int_channel("one", c0, c1)
  go int_channel("two", c1, c2)
  go int_channel("three", c2, c3)

  c0 <- 1
  c0 <- 10
  c0 <- 100
  c0 <- 1000
  c0 <- 10000
  c0 <- 100000
  close(c0)

  fmt.Println("Sent all numbers to c0")

  for x := range c3 {
    fmt.Printf("out: %d
", x)
  }
}
  • 写回答

2条回答 默认 最新

  • dongran1779 2016-07-02 10:51
    关注

    It hangs because the loop which reads from the output channel is never reached, thus the channels are not "emptyed" and once each channe has a value written into it no progress can be made and program hangs. To fix it write to the input in another goroutine, ie

    func main() {
      c0 := make(chan int)
      c1 := make(chan int)
      c2 := make(chan int)
      c3 := make(chan int)
    
      go int_channel("one", c0, c1)
      go int_channel("two", c1, c2)
      go int_channel("three", c2, c3)
    
      go func(){
        c0 <- 1
        c0 <- 10
        c0 <- 100
        c0 <- 1000
        c0 <- 10000
        c0 <- 100000
        fmt.Println("Sent all numbers to c0")
        close(c0)
      }()
    
    
      for x := range c3 {
        fmt.Printf("out: %d
    ", x)
      }
    }
    

    IOW, when the line c0 <- 1 is executed, the value flows throught all three cannels and ends up in c3, but since the reader loop is not reached yet, it just "sits in there". Then the line c0 <- 10 is executed, and this value ends up in c2 because it can't be written into c3 - the previous value is still in there, blocking the write. And thus when the line c0 <- 100 is executed, all channels are full and no further progress can be made.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?