问题描述
在诸如图书馆之类的大型项目中使用 atexit
有内在的危险吗?
Are there inherent dangers in using atexit
in large projects such as libraries?
如果是的话,那是什么?是关于 atexit
背后的技术性质的,它可能导致大型项目出现问题?
If so, what is it about the technical nature behind atexit
that may lead to problems in larger projects?
推荐答案
我避免在库中使用 atexit
的主要原因是对它的任何使用都涉及全局状态。一个好的图书馆应该避免具有全局状态。
The main reason I would avoid using atexit
in libraries is that any use of it involves global state. A good library should avoid having global state.
但是,还有其他技术原因:
However, there are also other technical reasons:
-
实现仅需支持少量(我认为是32个)
atexit
处理程序。之后,可能所有对atexit
的调用都将失败,或者根据资源的可用性而成功或失败。因此,如果您无法注册您的atexit
处理程序,那么您就必须处理该怎么办,而可能没有任何好的方法进行处理。
Implementations are only required to support a small number (32, I think) of
atexit
handlers. After that, it's possible that all calls toatexit
fail, or that they succeed or fail depending on resource availability. Thus, you have to deal with what to do if you can't register youratexit
handler, and there might not be any good way to proceed.
atexit
与 dlopen
的交互或其他动态加载库的方法没有定义。已注册 atexit
处理程序的库无法安全地卸载,并且不同的实现处理这种情况的方式可能会有所不同。
Interaction of atexit
with dlopen
or other methods of loading libraries dynamically is not defined. A library which has registered atexit
handlers cannot safely be unloaded, and the ways different implementations deal with this situation can vary.
写得不好的 atexit
处理程序可能彼此交互,或者只是不良行为,从而阻止程序正确退出。例如,如果 atexit
处理程序试图获取另一个线程中持有的锁,并且由于时的状态而无法释放该锁。退出
。
Poorly written atexit
handlers could have interactions with one another, or just bad behaviors, that prevent the program from properly exiting. For instance, if an atexit
handler attempts to obtain a lock that's held in another thread and that can't be released due to the state at the time exit
was called.
这篇关于atexit是否有害?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!