QThreads 是否控制推向它的堆栈创建的 QObjects 的销毁?

Do QThreads control destruction of stack-created QObjects pushed to it?

我是 python 的 Qt (PySide) 新手,正在研究 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 创建工作者对象,然后将线程的 finished() 信号连接到工作者的 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()