Qt 6.11 is out! See what's new in the release
blog
QThread events not ocurring as expected
-
Hello,
I've got this code:worker.h
class Worker : public QObject { public: Worker() {} public slots: void operate() { while(!QThread::currentThread()->isInterruptionRequested()) { qDebug() << "Operating"; } } };Core.h
class Core : public QObject { public: Core() { worker.moveToThread(&myThread); connect(&myThread, &QThread::started, &worker, &Worker::operate); connect(&myThread, &QThread::started, this, [=] { qDebug() << "thread started"; }); connect(&myThread, &QThread::finished, this, [=] { qDebug() << "thread finished"; }); QTimer::singleShot(1000, this, [=] { myThread.requestInterruption(); myThread.quit(); }); myThread.start(); } private: QThread myThread; Worker worker; };main.cpp
#include <QCoreApplication> #include "core.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Core core; return a.exec(); }And output is:
Operating Operating ... Operating thread started thread finishedI'm expecting this output:
thread started Operating ... Operating thread finishedWhat I'am missing?
-
Slots are executed in the order of connection. if you simply move
connect(&myThread, &QThread::started, &worker, &Worker::operate);belowconnect(&myThread, &QThread::started, this, [=] { qDebug() << "thread started";});then the output should be what you expect.P.S.
Allocatingworkeron the stack can create problems as it can go out of scope in the main thread and get deleted while the secondary thread is still working on it