PDA

View Full Version : Unable to abort the worker thread using singleshot timer



rawfool
5th July 2017, 11:49
I have a Worker class with doWork() function/slot where in I do stuff using while loop coupled with QThread. I'm trying to break out of loop using a singleshot timer but doesn't seem to be working though.
Could someone guide me what's wrong in my code. Thanks.



#include <QCoreApplication>
#include <QThread>
#include <QTime>
#include <QTimer>
#include <QDebug>

class Worker : public QObject
{
Q_OBJECT
int m_continue;
public:
Worker() : m_continue(1)
{
qDebug() << "Worker::Ctor";
QTimer::singleShot(7000, this, SLOT(discontinue())); // Expecting to call discontinue() after 7 secs.
}
~Worker() { qDebug() << "Worker::Dtor"; }
private slots:
void doWork()
{
while(m_continue)
{
qDebug() << QTime::currentTime().toString("HH:mm");
QThread::sleep(2);
}
emit done();
qDebug() << "Done!";
}
void discontinue()
{
qDebug() << "Aborting ...";
m_continue = 0;
}
signals:
void done();
};

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QThread thread;
Worker worker;
worker.moveToThread(&thread);
QCoreApplication::connect(&thread, SIGNAL(started()), &worker, SLOT(doWork()));
QCoreApplication::connect(&worker, SIGNAL(done()), &thread, SLOT(quit()));
QCoreApplication::connect(&worker, SIGNAL(done()), &worker, SLOT(deleteLater()));
QCoreApplication::connect(&thread, SIGNAL(finished()), &thread, SLOT(deleteLater()));
thread.start();

return a.exec();
}

#include "main.moc"

Lesiok
5th July 2017, 12:06
Try to change dWork to this.
void doWork()
{
if(m_continue)
{
qDebug() << QTime::currentTime().toString("HH:mm");
QTimer::singleShotQThread(2000, this, SLOT(doWork()));
}
else
{
emit done();
qDebug() << "Done!";
}
}
While loop is blocking event loop in thread.

rawfool
5th July 2017, 12:16
Thank you.

rawfool
7th July 2017, 07:32
Given the scenario with QThreads implementation using Worker object, what would be the correct way to implement a QThread to run continuously and with a option to abort it when required.
What I looking for is, if the above method just enough or is there a better way to do it?
Thanks!

Santosh Reddy
7th July 2017, 11:29
It is simple & sufficient.

Lesiok
7th July 2017, 12:43
You have to remember : if You want to communicate with Worker via signals and slots You can not block thread event loop.