Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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 finished
    

    I'm expecting this output:

    thread started
    Operating
    ...
    Operating
    thread finished
    

    What I'am missing?



  • Slots are executed in the order of connection. if you simply move connect(&myThread, &QThread::started, &worker, &Worker::operate); below connect(&myThread, &QThread::started, this, [=] { qDebug() << "thread started";}); then the output should be what you expect.

    P.S.
    Allocating worker on 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



  • Slots are executed in the order of connection. if you simply move connect(&myThread, &QThread::started, &worker, &Worker::operate); below connect(&myThread, &QThread::started, this, [=] { qDebug() << "thread started";}); then the output should be what you expect.

    P.S.
    Allocating worker on 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



  • Worked. I was looking solution in wrong direction.

    Thanks for advice!


Log in to reply