package main
func main() {
ch1 := make(chan int)
go pump(ch1) // pump hangs
}
func pump(ch chan int) {
ch <- 1
ch <- 2
}
为什么写腐败没有错?阻止主进程将死锁
答案 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