douzhun8615 2019-01-21 13:39
浏览 6

如何等待恐慌的goroutine?

A common way to wait for a goroutine is to use a *sync.WaitGroup:

func main() {
    wg := &sync.WaitGroup{}
    wg.Add(1)
    go func() {
        defer wg.Done()
        // Long running task
    }()
    wg.Wait()
}

No problems here. However, what about this:

func main() {
    wg := &sync.WaitGroup{}
    wg.Add(1)
    go func() {
        defer wg.Done()
        // Long running task
        panic("Something unexpected happened.")
    }()
    wg.Wait()
}

In this case, when wg.Done() is called, I believe main() could exit without details of panic() ever being written to stdout/stderr. Is this true and if yes, how might I prevent it from happening?

  • 写回答

2条回答 默认 最新

  • dqsvf28682 2019-01-21 13:46
    关注

    The panic will kill the process regardless, because no one is recovering from it. If you want to recover from panics in a goroutine, you must have recover wrapping the call stack in the same goroutine.

    wg.Done will be called in this case, by the defer statement. But the process may die before the main goroutine finishes the wg.Wait anyway.

    评论

报告相同问题?

悬赏问题

  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow