【发布时间】:2014-10-10 01:15:48
【问题描述】:
请帮助我理解为什么在这种情况下没有接收入站<-done 频道?
func main() {
done := make(chan bool)
println("enter")
defer func() {
println("exit")
}()
defer func() {
println(" notify start")
done <- true
println(" notify end")
}()
go func() {
println(" wait start")
<-done
println(" wait end")
}()
time.Sleep(time.Millisecond) // << when this is removed, it works.
}
我希望输出是:
enter
notify start
wait start
wait end
notify end
exit
但实际上是:
enter
wait start
notify start
notify end
exit
我最初认为done 通道以某种方式被提前关闭或清理,但即使done 是全局的,它也会导致相同的意外行为。
在done <- true 出现之前,<-done 不应该阻塞吗?反之亦然?
分辨率
似乎我希望程序在退出之前等待所有 goroutines 完成。这是一个错误的假设。
这是一个肮脏的解决方法:
func main() {
done, reallydone := make(chan bool), make(chan bool)
println("enter")
defer func() {
<-reallydone
println("exit")
}()
go func() {
println(" wait start")
<-done
println(" wait end")
reallydone <- true
}()
defer func() {
println(" notify start")
done <- true
println(" notify end")
}()
time.Sleep(time.Millisecond)
}
【问题讨论】: