在生成goroutine的库中发生的恐慌

huangapple go评论68阅读模式
英文:

Panics in libraries that spawn goroutines

问题

如果一个导入的库生成了一个可能引发 panic 的 goroutine,开发者无法阻止程序退出。

就像在这段代码中,使用延迟恢复调用一个有问题的库是无效的,因为该库生成了一个会引发 panic 的 goroutine,而这个 panic 无法被主函数的恢复机制捕获。

我理解得对吗?唯一的解决方法就是在选择项目的依赖时非常小心,并希望作者不会做类似的事情。

英文:

What if an imported library spawns a goroutine that can panic? In this case, there is nothing a developer can do to stop the program from exiting.

Like in this code, calling a bad library with deferred recover does not help as the library is spawning a goroutine that panics, and it cannot be caught by the main's recover.

Do I understand it correct that the only remedy is to be very careful when choosing dependencies for one's project and hope that the authors do not do something similar?

package main

import (
	"fmt"
	"time"
)

func main() {
	defer func() {
		r := recover()
		if r != nil {
			fmt.Println("panic caught")
		}
	}()

	badLibrary()
}

func badLibrary() {
	go recklessFunction()
	time.Sleep(time.Second)
}

func recklessFunction() {
	panic("something went wrong")
}

答案1

得分: 5

你是对的,你对此无能为力。如果一个依赖项调用了os.Exit(),你也无法做任何事情。

将goroutine作为库来启动通常是不好的实践,让客户端(库的用户)选择是否需要并发执行(goroutine),添加go关键字是微不足道的。当然,也有例外情况。

英文:

You're right, you can't do anything about that. Neither can you if a dependency calls os.Exit() for example.

Launching goroutines as a library is often bad practice anyway, let the client (user of the library) choose if concurrent execution (a goroutine) is wanted, adding the go keyword is trivial. There are exceptions of course.

huangapple
  • 本文由 发表于 2021年12月30日 23:51:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/70533828.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定