【发布时间】:2014-11-15 06:17:41
【问题描述】:
我想知道在退出程序之前等待 goroutine 完成的正确方法是什么。阅读其他一些答案,bool chan 似乎可以解决问题,如Playground link
func do_stuff(done chan bool) {
fmt.Println("Doing stuff")
done <- true
}
func main() {
fmt.Println("Main")
done := make(chan bool)
go do_stuff(done)
<-done
//<-done
}
我有两个问题:
为什么
如果我取消最后一行的注释会发生什么?我有一个死锁错误。这是因为通道是空的,没有其他函数向它发送值吗?
【问题讨论】:
-
<- done有效,因为这正是频道所做的 :)(有关详细信息,请参阅 golang.org/ref/spec#Receive_operator 和 golang.org/ref/spec#Send_statements)。关于取消注释第二行如何导致僵局,您是对的。没有任何东西发送到done并且 Go 认识到,如果它等待,甚至没有任何东西 可以(例如,没有任何东西在等待网络调用)。