Unable to abort the worker thread using singleshot timer
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.
Code:
#include <QCoreApplication>
#include <QThread>
#include <QTime>
#include <QTimer>
#include <QDebug>
{
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");
}
emit done();
qDebug() << "Done!";
}
void discontinue()
{
qDebug() << "Aborting ...";
m_continue = 0;
}
signals:
void done();
};
int main(int argc, char *argv[])
{
Worker worker;
worker.moveToThread(&thread);
QCoreApplication::connect(&worker,
SIGNAL(done
()),
&worker,
SLOT(deleteLater
()));
QCoreApplication::connect(&thread,
SIGNAL(finished
()),
&thread,
SLOT(deleteLater
()));
thread.start();
return a.exec();
}
#include "main.moc"
Re: Unable to abort the worker thread using singleshot timer
Try to change dWork to this.
Code:
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.
Re: Unable to abort the worker thread using singleshot timer
Re: Unable to abort the worker thread using singleshot timer
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!
Re: Unable to abort the worker thread using singleshot timer
It is simple & sufficient.
Re: Unable to abort the worker thread using singleshot timer
You have to remember : if You want to communicate with Worker via signals and slots You can not block thread event loop.