我是 Qt (PySide) for python 的新手,正在研究 QThread 的良好使用。
我有一个工作线程和一个工作对象,后者在构建后被移入工作线程。
class Foo:
def __init__(self):
self.barThread = QThread()
self.barWorker = barWorker()
self.barWorker.moveToThread(self.barThread)
我的问题是,在移动到新线程后,barWorker 是否在 barThread 结束时被销毁?
因为我更愿意这样做(防止以线程不安全的方式访问对象),但是尽管工作线程被传递到新线程,但它似乎被垃圾回收了。
class Foo:
def __init__(self):
self.barThread = QThread()
def startWork(self):
barWorker = BarWorker()
barWorker.moveToThread(self.barThread)
谢谢。
最佳答案
线程不拥有移动到它的对象的所有权,因此它也不承担删除它们的责任。所发生的只是对象的线程亲和性发生了变化。工作对象的清理完全由调用者负责。
在 C++ 中,您可以使用 new
创建 worker 对象,然后将线程的 finished()
信号连接到 worker 的 deleteLater()
投币口。但这在 Python 中不会真正起作用,因为没有指针。一种可能的解决方法是使用函数外壳来维护临时引用,而不是:
def startWork(self):
worker = Worker()
worker.moveToThread(self.thread)
worker.finished.connect(self.thread.quit)
self.thread.started.connect(worker.process)
def cleanup():
self.thread.started.disconnect(worker.process)
self.thread.finished.disconnect(cleanup)
worker.deleteLater()
self.thread.finished.connect(cleanup)
self.thread.start()
关于python - QThreads 是否控制推向它的堆栈创建的 QObjects 的销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29197012/