Issue
I'm new to Qt (PySide) for python, looking into good QThread use.
I have a worker thread and worker object, the latter gets moved into the worker thread after construction.
class Foo:
def __init__(self):
self.barThread = QThread()
self.barWorker = barWorker()
self.barWorker.moveToThread(self.barThread)
My question is, after moving to the new thread, is the barWorker destroyed when barThread ends?
Because I'd prefer to do this (prevents accessing the object in a thread-unsafe way), but the worker appears to be garbage collected despite being passed to a new thread.
class Foo:
def __init__(self):
self.barThread = QThread()
def startWork(self):
barWorker = BarWorker()
barWorker.moveToThread(self.barThread)
Thanks.
Solution
A thread doesn't take ownership of the objects moved to it, and so it doesn't assume responsibility for deleting them, either. All that happens is that the thread affinity of the objects is changed. Cleanup of worker objects is entirely the responsibility of the caller.
In C++, you could create the worker object with new
and then connect the thread's finished()
signal to the worker's deleteLater()
slot. But that won't really work in Python, because there's no pointers. One possible work-around would be to use a function enclosure to maintain a temporary reference, instead:
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()
Answered By - ekhumoro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.