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.

Qt Code:
  1. #include <QCoreApplication>
  2. #include <QThread>
  3. #include <QTime>
  4. #include <QTimer>
  5. #include <QDebug>
  6.  
  7. class Worker : public QObject
  8. {
  9. Q_OBJECT
  10. int m_continue;
  11. public:
  12. Worker() : m_continue(1)
  13. {
  14. qDebug() << "Worker::Ctor";
  15. QTimer::singleShot(7000, this, SLOT(discontinue())); // Expecting to call discontinue() after 7 secs.
  16. }
  17. ~Worker() { qDebug() << "Worker::Dtor"; }
  18. private slots:
  19. void doWork()
  20. {
  21. while(m_continue)
  22. {
  23. qDebug() << QTime::currentTime().toString("HH:mm");
  24. QThread::sleep(2);
  25. }
  26. emit done();
  27. qDebug() << "Done!";
  28. }
  29. void discontinue()
  30. {
  31. qDebug() << "Aborting ...";
  32. m_continue = 0;
  33. }
  34. signals:
  35. void done();
  36. };
  37.  
  38. int main(int argc, char *argv[])
  39. {
  40. QCoreApplication a(argc, argv);
  41. QThread thread;
  42. Worker worker;
  43. worker.moveToThread(&thread);
  44. QCoreApplication::connect(&thread, SIGNAL(started()), &worker, SLOT(doWork()));
  45. QCoreApplication::connect(&worker, SIGNAL(done()), &thread, SLOT(quit()));
  46. QCoreApplication::connect(&worker, SIGNAL(done()), &worker, SLOT(deleteLater()));
  47. QCoreApplication::connect(&thread, SIGNAL(finished()), &thread, SLOT(deleteLater()));
  48. thread.start();
  49.  
  50. return a.exec();
  51. }
  52.  
  53. #include "main.moc"
To copy to clipboard, switch view to plain text mode