I found this QThread example from here. It recommends to use QObject and QThread over than subclassing QThread.
class Worker : public QObject
{
Q_OBJECT
public slots:
void doWork() {
/* ... */
}
};
QThread *thread = new QThread;
Worker *worker = new Worker;
worker->moveToThread(thread);
thread->start();
QMetaObject::invokeMethod(worker, "doWork", Qt::QueuedConnection);
My first question is when and how to delete the thread?
I have tried to connect finished to 2 slots, myTest and deleteLater. And I set a breakpoint in myTest, this never got triggered. So I suspect there is no finished signal, which mean the thread would not be deleted.
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), this, SLOT(myTest()));
For the worker object, I emit a finished signal as the last instruction in doWork, and connect it to a slot in which I can delete the worker object. Is this the right way?
Qt version: 4.6.2
Your thread exits normally when its worker
method execution completed, but if you want to do some things in thread exit time, use the finished()
signal and it is possible to deallocate objects that live in thread that has just ended, by connecting the finished()
signal to QObject::deleteLater()
:
connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With