相关疑难解决方法(0)

为什么`推迟恢复()`不会引起恐慌?

为什么呼叫defer func() { recover() }()成功恢复恐慌goroutine,但呼叫defer recover()不?

作为一个简约的例子,这段代码并不恐慌

package main

func main() {
    defer func() { recover() }()
    panic("panic")
}
Run Code Online (Sandbox Code Playgroud)

但是,用恢复直接替换匿名函数恐慌

package main

func main() {
    defer recover()
    panic("panic")
}
Run Code Online (Sandbox Code Playgroud)

go deferred-execution

14
推荐指数
2
解决办法
2549
查看次数

呼叫者如何从子Goroutine的恐慌中恢复过来

我曾经认为,如果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")
    }

Run Code Online (Sandbox Code Playgroud)

我发现无论调用者函数完成与否,如果goroutines开始出现恐慌,调用者的延迟恢复机制都将无济于事。整个程序仍然无效。

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

recover go panic goroutine

3
推荐指数
1
解决办法
1459
查看次数

如果另一个 goroutine 崩溃了,如何保持 goroutine 运行?

我一直在试图找到一些东西来回答这个问题,但我找不到任何谈论它的东西。

假设我在 Go 中有一个函数,如下所示:

func main() {
    // assume this wrapped in a waitgroup or something 
    // so that it doesnt exit
    go queue.ConsumeAndDoSomething()
    go api.StartServer()
}
Run Code Online (Sandbox Code Playgroud)

我这里有两个 goroutine,它们做完全不同的事情,理想情况下,如果另一个 goroutine 崩溃/恐慌,一个应该继续运行。如果队列操作失败,API 服务器应该会受到影响,反之亦然。

我不确定这是否可能(甚至推荐)。有没有一种干净的方法可以做到这一点,或者一旦 Goroutine 发生恐慌,整个程序应该退出吗?

concurrency go goroutine

3
推荐指数
1
解决办法
3956
查看次数

标签 统计

go ×3

goroutine ×2

concurrency ×1

deferred-execution ×1

panic ×1

recover ×1