信号处理程序可以在PyQt中泄漏内存吗? [英] Can signal handlers memory leak in PyQt?
问题描述
简短问题:
可以通知处理程序内存泄漏.
Can signal handlers memory leak.
常见问题:
在C#中,如果我将处理程序附加到事件
In C#, if I attach a handler to an event
left_object.left_event += right_object.right_handler
然后,当我摆脱right_object
时,我需要删除该处理程序,否则垃圾收集器将永远不会处理它(因为left_object.left_event
保留了指向right_object
的指针)
Then I need to remove the handler when I get rid of right_object
or the garbage collector will never dispose of it (since left_object.left_event
retains a pointer to right_object
)
PyQt 信号和插槽也是如此.
Is the same also true of PyQt signals and slots.
left_object.left_signal.connect( right_object.right_handler )
我从这个问题中看到,Qt会自动断开信号和插槽的链接,当调用left_object
或right_object
的析构函数时,但是在Python中,我无法显式调用该析构函数,并且right_handler
是普通函数.
I see from this question that Qt automatically delinks signals and slots, when the destructor of either left_object
or right_object
is called, but in Python I cannot explicitly call the destructor, and right_handler
is a plain-old-function.
我是否需要删除处理程序以防止right_object
的内存泄漏,还是PyQt使用某种弱引用?
Do I need to remove the handler to prevent right_object
s memory-leaking, or does PyQt use some sort of weak-referencing?
虽然其中一个答案与此相关,但这个类似的问题询问PyQt如何处理lambda表达式内的对象,而不是PyQt如何处理信号.
While one of the answers touches on this, this similar question asks about how PyQt handles objects inside lambda expressions, not how PyQt handles signals.
推荐答案
使用此设计可能会导致内存泄漏.如果这些连接包含使对象保持活动状态的引用,则需要断开信号和插槽的连接.
It is possible to have a memory leak with this design. You need to disconnect the signals and slots if those connections contain references which are keeping objects alive.
这是否实际发生取决于right_handler
的确切含义.如果right_handler
是对self
的引用的闭包,则您有此问题.
Whether or not this actually happens depends on what exactly right_handler
is. If right_handler
is a closure with a reference to self
then you have this problem.
这篇关于信号处理程序可以在PyQt中泄漏内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!