How to properly delete threads& objects in them ?
-
Hey
I'd like to delete a bunch of threads & every object that is used by these threads... what is the proper approach to perform that action ?
class myObj : public QObject { Q_OBJECT public: myObj(QObject *p = nullptr) : QObject(p) { } ~myObj() { qDebug() << "My obj is dyin!" << this; } }; class myThread : public QThread { Q_OBJECT public: myThread() { } ~myThread() { qDebug() << "My thread dying " << this; } }; int main(int argc, char *argv[]) { auto app = QApplication(argc, argv); QWidget w; w.show(); auto t = new myThread(); auto ob = new myObj(&w); auto otherOb = new QTcpSocket(ob); qDebug() << "Made thread : " << t; qDebug() << "Made object : " << ob << ob->parent() << ob->thread(); ob->setParent(nullptr); ob->moveToThread(t); QMetaObject::invokeMethod(ob, [&, thread = t, object = ob]() { object->setParent(thread); }, Qt::QueuedConnection); ob->setParent(t); qDebug() << "Made object : " << ob << ob->parent() << ob->thread(); t->start(); t->terminate(); t->deleteLater(); app.processEvents(); uint time = 0; while (time < 100) { time++; QThread::msleep(10); app.processEvents(); } qDebug() << "Thread : " << t; qDebug() << "ob : " << ob->thread(); ob->moveToThread(app.thread()); ob->deleteLater(); qDebug() << "ob2 : " << ob->thread(); app.exec(); return 1; }
I'm getting stuck/lost. Say if I delete the thread, then calling
ob->deleteLater()
will be useless as there won't be any event loop able to handle the request? Since the thread will be gone... any ideas? -
Hi
One way is to use the signal from the thread
connect(Thread, &QThread::finished, worker, &WorkerObject::deleteLater);Do notice that using terminate is not recommended
https://doc.qt.io/qt-5/qthread.html#terminate
Its sort of "violent" :)Normally you do
Thread->quit();
Thread->wait(); -
@mrjj Ahh I mess up with that termination, I mixed it up with the other one in my head and never checked 2x docs... yeah quit() works as I expected and object now dies properly. Thanks!
So in general, moving object to another thread does not set the thread as it parent does it.
-
@Dariusz said in How to properly delete threads& objects in them ?:
So in general, moving object to another thread does not set the thread as it parent does it.
No because the function is called
moveToThread
and notmoveToThreadAndDoOtherStuffLikeSettingaParent