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

时间:2018-06-08 01:14:08

标签: go goroutine

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

为什么写腐败没有错?阻止主进程将死锁

1 个答案:

答案 0 :(得分:2)

因为main()函数退出并终止程序,而pump()goroutine被阻止写入通道。

我认为这段代码符合您的期望:

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
}

输出:

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

游乐场:https://play.golang.org/p/FTFPOBCm4G_0