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

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

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)