Confusion about QThread & deleteLater
-
I have a problem with how Qt handles objects destruction related to
QThread
.m_worker->moveToThread(m_thread); connect(m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
m_thread
belongs to the UI main thread, aftermoveToThread
them_worker
thread affinity belongs to the sub thread. So theAUTO
connection should beQt::QueuedConnection
which leadsdeleteLater
to execute in the sub thread.- However, the thread has been finished and the thread event loop is stopped,
deleteLater
may never be executed. (I knowdeleteLater
is asynchronous, maybedeleteLater
is executed but the real "delete" may never be handled in the sub thread event loop?)
It seems a paradox, what's the real problem here? I have read
QObject::deleteLater
here but still feel confused. Thanks a lot for answering! -
I have a problem with how Qt handles objects destruction related to
QThread
.m_worker->moveToThread(m_thread); connect(m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
m_thread
belongs to the UI main thread, aftermoveToThread
them_worker
thread affinity belongs to the sub thread. So theAUTO
connection should beQt::QueuedConnection
which leadsdeleteLater
to execute in the sub thread.- However, the thread has been finished and the thread event loop is stopped,
deleteLater
may never be executed. (I knowdeleteLater
is asynchronous, maybedeleteLater
is executed but the real "delete" may never be handled in the sub thread event loop?)
It seems a paradox, what's the real problem here? I have read
QObject::deleteLater
here but still feel confused. Thanks a lot for answering!@KtrNozomi "If deleteLater() is called on an object that lives in a thread with no running event loop, the object will be destroyed when the thread finishes."
https://doc.qt.io/qt-6/qobject.html#deleteLater -
@KtrNozomi "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."
https://doc.qt.io/qt-6/qthread.html#finished -