In what thread would a QObject be deleted if it was moved to another QThread?
-
The one can read here (emphs are mine) :
The logging itself (
LogWorker::logEvent
) will always be done in the same thread, therefore this approach is working well for classes requiring thread-affinity. At the same time,LogWorker
constructor and destructor are executed in the main thread (specifically the threadLogService
is running in), and therefore ...I repeat the essential part of code here :
class LogService : public QObject { ... private: QThread *thread; LogWorker *worker; }; // implementation LogService::LogService(QObject *parent) : QObject(parent) { thread = new QThread(this); worker = new LogWorker; worker->moveToThread(thread); connect(this, &LogService::logEvent, worker, &LogWorker::logEvent); connect(thread, &QThread::finished, worker, &QObject::deleteLater); thread->start(); } LogService::~LogService() { thread->quit(); thread->wait(); }
Ok. It's obvious that the ctor is called in the main thread (we haven't moved the
LogWorker
yet). But what about the dtor? As stated in the documentation :[
QThread::finished
]When this signal is emitted, the event loop has already stopped running. No more events will be processed in the thread, except for deferred deletion events. This signal can be connected to QObject::deleteLater(), to free objects in that thread.
and
[
Qt::QueuedConnection
]The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
and
[Per thread Event Loop]
Calling delete on a QObject from a thread other than the one that owns the object (or accessing the object in other ways) is unsafe, unless you guarantee that the object isn't processing events at that moment. Use QObject::deleteLater() instead, and a DeferredDelete event will be posted, which the event loop of the object's thread will eventually pick up. By default, the thread that owns a QObject is the thread that creates the QObject, but not after QObject::moveToThread() has been called.
According to this I would say the dtor must be called and executed in the secondary thread not the main one. Am I right?
-
@LRDPRDX said in In what thread would a QObject be deleted if it was moved to another QThread?:
the dtor must be called and executed in the secondary thread not the main one. Am I right?
Correct, that's what
connect(thread, &QThread::finished, worker, &QObject::deleteLater);
does and as you noted>No more events will be processed in the thread, except for deferred deletion events.
Do the
deleteLater
will still picked up after thefinished
is emitted and the destructor will run in the secondary thread