引用计数下降到零后调用`__del__`多少时间? [英] how soon is `__del__` called after reference count drops to zero?

查看:105
本文介绍了引用计数下降到零后调用`__del__`多少时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在引用计数达到零后的多少时间是 __ del __ 方法调用?该语言是否承诺在任何其他使用代码可以执行之前立即完成?或者每个实现都可以做它喜欢的事情,可能会延迟调用 __ del __ 任意长? b $ b

请忽略情况当程序即将退出时(我认为这意味着给定块中的最后一个语句已完成,并且堆栈为空)。我知道在这种情况下,没有关于 __ del __ 的承诺。它甚至可能根本不会被调用。

另外,我知道引用计数可能由于周期等原因而不为零。在这里我不关心这个问题(我在问一个单独的问题关于它)。

解决方案

Python对 __ del __ 被调用,或者是否被调用。实际上,如果对象是引用循环的一部分,则不可能调用 __ del __ 方法,因为即使整个循环被清除,Python也没有办法决定在哪里打破循环,并按照什么顺序调用 __ del __ 方法(如果有的话)。由于 __ del __ 的相当古怪的语义(为了调用 __ del __ ,对象的refcount临时增加,并且 __ del __ 方法可以通过在其他地方存储引用来防止对象被破坏)其他实现中会发生什么是一个废话。 (我不记得当前Jython中的具体细节,但过去它已经改变了几次。)



也就是说,在CPython中,if __ del __ 被调用,只要引用计数降到零就会调用它(因为refcounting是唯一的方法 __ del __ 方法被调用,并且CPython调用 __ del __ 的唯一机会是当实际的引用计数改变时。)


How soon after the reference count reaches zero is __del__ method called? Does the language promise that it's done right away, before any other use code can execute? Or can each implementation do what it likes, potentially delaying the call to __del__ arbitrarily long?

Please ignore the situation when the program is about to exit (I assume it means the last statement in the given block has finished, and the stack is empty). I understand that in such cases, there's no promises about __del__; it may not even be called at all.

Also, I'm aware that reference count may be non-zero due to cycles, etc. I am not concerned about that here (I'm asking a separate question about it).

解决方案

Python doesn't make any guarantees about when __del__ is called, or whether it is called at all. As it is, __del__ methods are unlikely to be called if the object is part of a reference cycle, because even if the cycle as a whole is cleaned up, Python has no way to decide where to break the cycle and in what order the __del__ methods (if any) should be called. Because of __del__'s rather quirky semantics (in order to call __del__ the refcount of the object is temporarily increased, and the __del__ method can prevent destruction of the object by storing the reference somewhere else) what happens in other implementations is a bit of a crapshoot. (I don't remember the exact details in current Jython, but it has changed a few times in the past.)

That said, in CPython, if __del__ is called, it's called as soon as the reference count drops to zero (since refcounting is the only way __del__ methods are called, and the only chance CPython has of calling __del__ is when the actual refcount is changed.)

这篇关于引用计数下降到零后调用`__del__`多少时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆