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

how signal and slots is working here



  • In code below,the slot(STOP()) is running in main thread.As per my knowledge if we use direct connection then and only then the slot will run into sender's thread.

    #if QT_VERSION>=0x050000
    #include <QtWidgets>
    #else
    #include <QtGui>
    #endif
    
    class Thread : public QThread
    {
        Q_OBJECT
    
    public:
        Thread():m_stop(false)
        {}
    
    public slots:
        void stop()
        {
            qDebug()<<"Thread::stop called from main thread: "<<currentThreadId();
            QMutexLocker locker(&m_mutex);
            m_stop=true;
        }
    
    private:
        QMutex m_mutex;
        bool m_stop;
    
        void run()
        {
            qDebug()<<"From worker thread: "<<currentThreadId();
            while (1) {
                {
                QMutexLocker locker(&m_mutex);
                if (m_stop) break;
                }
                msleep(10);
            }
        }
    };
    
    #include "main.moc"
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        qDebug()<<"From main thread: "<<QThread::currentThreadId();
        QPushButton btn("Stop Thread");
        Thread t;
    
        QObject::connect(&btn, SIGNAL(clicked()), &t, SLOT(stop()));
        QObject::connect(&t, SIGNAL(finished()), &a, SLOT(quit()));
    
        t.start();
        btn.show();
        return a.exec();
    }
    

    The output is more or less like

    From main thread: 0x13a8
    From worker thread: 0xab8
    Thread::stop called from main thread: 0x13a8

    i really not understand the reason behind it.how stop() slot is running in mainthread.i checked it by putting directconnection ,i got the same result.stop() is running in main thread.what could be reason?



  • Hi,

    That's because QThread lives in the main thread. Only run() is executed in a different thread.

    edit: I think this post could help you https://forum.qt.io/post/453541


Log in to reply