douji6896 2015-12-10 07:39
浏览 28
已采纳

如何从等待组调用的函数中捕获运行时错误?

How to handle crushes in a waitgroup gracefully?

In other words, in the following snippet of code, how to catch the panics/crushes of gorourines invoking method do()?

func do(){
    str := "abc"
    fmt.Print(str[3])
    defer func() {
        if err := recover(); err != nil {
            fmt.Print(err)
        }
    }()
}

func main() {
    var wg sync.WaitGroup

    for i := 0; i < 1; i++ {
        wg.Add(1)
        go do()
        defer func() {
            wg.Done()
            if err := recover(); err != nil {
                fmt.Print(err)
            }
        }()
    }
    wg.Wait()
    fmt.Println("This line should be printed after all those invocations fail.")
}
  • 写回答

2条回答 默认 最新

  • dongpobo6009 2015-12-10 07:48
    关注

    First, registering a deferred function to recover should be the first line in the function, as since you do it last, it won't even be reached because the line / code before the defer already panics and so the deferred function does not get registered which would restore the panicing state.

    So change your do() function to this:

    func do() {
        defer func() {
            if err := recover(); err != nil {
                fmt.Println("Restored:", err)
            }
        }()
        str := "abc"
        fmt.Print(str[3])
    }
    

    Second: this alone will not make your code work, as you call wg.Defer() in a deferred function which would only run once main() finishes - which is never because you call wg.Wait() in your main(). So wg.Wait() waits for the wg.Done() calls, but wg.Done() calls will not be run until wg.Wait() returnes. It's a deadlock.

    You should call wg.Done() from the do() function, in the deferred function, something like this:

    var wg sync.WaitGroup
    
    func do() {
        defer func() {
            if err := recover(); err != nil {
                fmt.Println(err)
            }
            wg.Done()
        }()
        str := "abc"
        fmt.Print(str[3])
    }
    
    func main() {
        for i := 0; i < 1; i++ {
            wg.Add(1)
            go do()
        }
        wg.Wait()
        fmt.Println("This line should be printed after all those invocations fail.")
    }
    

    Output (try it on the Go Playground):

    Restored: runtime error: index out of range
    This line should be printed after all those invocations fail.
    

    This of course needed to move the wg variable to global scope. Another option would be to pass it to do() as an argument. If you decide to go this way, note that you have to pass a pointer to WaitGroup, else only a copy will be passed (WaitGroup is a struct type) and calling WaitGroup.Done() on a copy will not have effect on the original.

    With passing WaitGroup to do():

    func do(wg *sync.WaitGroup) {
        defer func() {
            if err := recover(); err != nil {
                fmt.Println("Restored:", err)
            }
            wg.Done()
        }()
        str := "abc"
        fmt.Print(str[3])
    }
    
    func main() {
        var wg sync.WaitGroup
        for i := 0; i < 1; i++ {
            wg.Add(1)
            go do(&wg)
        }
        wg.Wait()
        fmt.Println("This line should be printed after all those invocations fail.")
    }
    

    Output is the same. Try this variant on the Go Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码