Using deleteLater() without main event loop
-
Hello,
I'm trying to properly stop and delete a qthread and its worker. The thread and the worker were created in a main application thread where no event loop is running.thread_ = new QThread(this), worker_ = new ActiveDevicePrivate(*this); worker_->moveToThread(thread_); thread_->start();
Later I want to stop the thread and delete it together with the worker.
thread_->quit(); thread_->wait(); thread_->deleteLater(); worker_->deleteLater();
But as I read the documentation I found this: If deleteLater() is called after the main event loop has stopped, the object will not be deleted. I assume that this is also my case (as after the main loop stopped or there is no main loop are probably the same things). Am I right? Using this code my objects won't be deleted? If that's true, how can I delete them properly? I tried to use just delete thread_, but it crashes the application.
-
Hi,
Since you're passing this as parameter of your QThread constructor, you don't seem to call in your main function, do you ?
-
Hello,
I'm trying to properly stop and delete a qthread and its worker. The thread and the worker were created in a main application thread where no event loop is running.thread_ = new QThread(this), worker_ = new ActiveDevicePrivate(*this); worker_->moveToThread(thread_); thread_->start();
Later I want to stop the thread and delete it together with the worker.
thread_->quit(); thread_->wait(); thread_->deleteLater(); worker_->deleteLater();
But as I read the documentation I found this: If deleteLater() is called after the main event loop has stopped, the object will not be deleted. I assume that this is also my case (as after the main loop stopped or there is no main loop are probably the same things). Am I right? Using this code my objects won't be deleted? If that's true, how can I delete them properly? I tried to use just delete thread_, but it crashes the application.
@sykac said in Using deleteLater() without main event loop:
worker_->deleteLater();
Always be careful with calling direct methods of an item that lives in a different thread. It's safer to
connect(thread_,&QThread::finished,worker_,&QObject::deleteLater);
just before you callthread_->quit();
. The worker will be cleaned up by the secondary thread event loop.thread_->deleteLater();
this will not work if you don't have an event loop in the main thread but, as @SGaist mentioned, if you pass a parent to it in the constructor it will get automatically deleted when the parents gets deleted/goes out of scope
-
@VRonin said in Using deleteLater() without main event loop:
It's safer to connect(thread_,&QThread::finished,worker_,&QObject::deleteLater); just before you call thread_->quit();.
I thought that's why thread_->wait() is called. I'll try to use the connect.