呼叫者如何从子Goroutine的恐慌中恢复 [英] How does a caller function to recover from child goroutine's panics

查看:344
本文介绍了呼叫者如何从子Goroutine的恐慌中恢复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经认为,goroutine中的紧急情况会在调用方在紧急情况之前完成后将其杀死(延迟恢复无法提供帮助,因为此时尚未发生紧急情况),

I used to think the panic in a goroutine will kill the program if its caller finishes before the panic (the deferred recovering gives no help since at that point there's no panic occurs yet),

直到我尝试以下代码:



    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开始恐慌,调用者的延迟恢复机制将无济于事.整个程序仍然无效.

I found no matter the caller function finishes or not, if the goroutines it starts panic, the caller's deferred recover mechanism will not help. The whole program is still dead.

那么,为什么?理论上,调用者功能仍在运行.当出现紧急情况时,调用者的延迟功能应该起作用(包括恢复).

So, WHY? Theoretically the caller function is still running. When the panics happen the caller's deferred functions should work (including the recovering).

推荐答案

规范说:

在执行函数F时,显式调用panic或运行时panic会终止F的执行.然后,照常执行F延迟的任何函数.接下来,将运行由F的调用者运行的所有延迟函数,依此类推,直到被执行的goroutine中顶级函数所延迟的任何延迟.此时,程序终止,并报告错误情况,包括紧急情况的参数值.此终止序列称为恐慌.

While executing a function F, an explicit call to panic or a run-time panic terminates the execution of F. Any functions deferred by F are then executed as usual. Next, any deferred functions run by F's caller are run, and so on up to any deferred by the top-level function in the executing goroutine. At that point, the program is terminated and the error condition is reported, including the value of the argument to panic. This termination sequence is called panicking.

由于fun2是在goroutine中执行的顶级函数,并且fun2无法从紧急状态中恢复,因此当fun2紧急状态时,程序将终止.

Because fun2 is the top-level function executing in the goroutine and fun2 does not recover from a panic, the program terminates when fun2 panics.

当goroutine执行fun2恐慌时,不会调用fun1中的延迟调用.

The deferred call in fun1 is not called when the goroutine executing fun2 panics.

一个goroutine无法从另一个goroutine的恐慌中恢复过来.

A goroutine cannot recover from a panic in another goroutine.

这篇关于呼叫者如何从子Goroutine的恐慌中恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆