【发布时间】:2018-05-28 05:57:24
【问题描述】:
我曾经认为如果调用者在恐慌之前完成,goroutine 中的恐慌会杀死程序(延迟恢复没有帮助,因为此时还没有发生恐慌),
直到我尝试了以下代码:
func fun1() {
fmt.Println("fun1 started")
defer func() {
if err := recover(); err != nil {
fmt.Println("recover in func1")
}
}()
go fun2()
time.Sleep(10 * time.Second) // wait for the boom!
fmt.Println("fun1 ended")
}
func fun2() {
fmt.Println("fun2 started")
time.Sleep(5 * time.Second)
panic("fun2 booom!")
fmt.Println("fun2 ended")
}
我发现无论调用者函数完成与否,如果它启动的 goroutines 恐慌,调用者的延迟恢复机制将无济于事。整个程序还是死了。
那么,为什么?理论上调用者函数仍在运行。当恐慌发生时,调用者的延迟函数应该可以工作(包括恢复)。
【问题讨论】:
标签: go goroutine recover panic