Python 从外部强制安全地终止并删除PyQt QThread
我有一个PyQt项目,其中继承类中定义的一些代码需要在单独的线程中运行 在理想情况下,如果请求中断,线程化代码将具有停止线程的标志检查,但如果线程化代码将暴露于外部模块,则不可能进行此类检查 在当前实现中,使用了QThread的Python 从外部强制安全地终止并删除PyQt QThread,python,multithreading,pyqt5,Python,Multithreading,Pyqt5,我有一个PyQt项目,其中继承类中定义的一些代码需要在单独的线程中运行 在理想情况下,如果请求中断,线程化代码将具有停止线程的标志检查,但如果线程化代码将暴露于外部模块,则不可能进行此类检查 在当前实现中,使用了QThread的terminate,并成功地终止了线程。稍后删除CustomThread时会出现问题,如果线程在类Arun内执行时发生强制终止,则该类将保留在内存中,并且gc。get\u referers指向run方法中的引用: <bound method CustomThread
terminate
,并成功地终止了线程。稍后删除CustomThread
时会出现问题,如果线程在类Arun
内执行时发生强制终止,则该类将保留在内存中,并且gc。get\u referers
指向run方法中的引用:
<bound method CustomThread.run of <A.CustomThread object at 0x000001D4F0A8AEE8>>
class A(QtCore.QObject):
def __init__(self, parent=None):
super().__init__(parent)
self.run_thread = CustomThread(self)
def run(self):
# Possibly long running code
# Can't have checks if close if being requested
while True:
pass
class CustomThread(QtCore.QThread):
def __init__(self, run_class):
super().__init__(run_class)
self.run_class = run_class
def run(self):
self.run_class.run()
# emit signals if successful or not
def deleteLater(self):
self.run_class.run_thread = None
self.run_class = None
super().deleteLater()
def __del__(self):
print("del thread: ", self)