doudu6100 2018-06-08 01:14
浏览 191
已采纳

为什么chan不会在goroution中陷入僵局?

package main
func main() {
    ch1 := make(chan int)
    go pump(ch1) // pump hangs
}
func pump(ch chan int) {
    ch <- 1
    ch <- 2
}

Why is it that there is nothing wrong with writing a corruption? Blocking the main process will deadlock

  • 写回答

1条回答 默认 最新

  • doupi8598 2018-06-08 01:47
    关注

    Because the main() function exits and terminates the program while the pump() goroutine is blocked writing to the channel.

    I think this code does what you expect:

    package main
    func main() {
        ch1 := make(chan int)
        done := make(chan struct{})
        go pump(ch1, done) // pump hangs
        <-done // wait for pump
    }
    func pump(ch chan int, done chan struct{}) {
        ch <- 1
        ch <- 2 // never reached
        close(done) // never reached
    }
    

    Output:

    fatal error: all goroutines are asleep - deadlock!
    
    goroutine 1 [chan receive]:
    main.main()
        /tmp/sandbox778506014/main.go:7 +0xc0
    
    goroutine 4 [chan send]:
    main.pump(0x1043a080, 0x1043a0c0)
        /tmp/sandbox778506014/main.go:10 +0x40
    created by main.main
        /tmp/sandbox778506014/main.go:6 +0xa0
    

    Playground: https://play.golang.org/p/FTFPOBCm4G_0

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

报告相同问题?

悬赏问题

  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”