Questions about QThread

If I create QThread and call one of its slots from another thread, will it be called in the context of the thread of the QThread object or from the context of the thread that made the call?

+3
source share
3 answers

If you execute a slot emitting a signal, it depends on the type of signal-to-slot connection you have. A slot connected to the signal through a direct connection will run in the emitter stream. A slot connected through the next connection will be executed in the receiver stream. See here: http://doc.qt.nokia.com/4.7/threads-qobject.html

If the slot is executed directly, with the object [QThread] → slot (), the slot will be executed in the thread that makes the call.

+4

.

0

The slot caused by the signal will start in the thread for which it is associated QObject. In the current thread, a slot called directly will be launched. Here is a test program that demonstrates.

Conclusion:

main() thread: QThread(0x804d470)
run() thread: Thread(0xbff7ed94)
onRunning() direct call; thread: Thread(0xbff7ed94)
onRunning() signaled; thread: QThread(0x804d470)

Testing program:

#include <QtCore>

class Thread : public QThread
{
    Q_OBJECT
public:

    void run()
    {
        qDebug() << "run() thread:" << QThread::currentThread();
        emit running();
    }

public slots:
    void onRunning()
    {
        qDebug() << "onRunning() thread:" << QThread::currentThread();
    }

signals:
    void running();
};

#include "threadTest.moc"

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    qDebug() << "main() thread:" << QThread::currentThread();

    Thread t;
    QObject::connect(&t, SIGNAL(running()), &t, SLOT(onRunning()));
    t.start();

    QTimer::singleShot(100, &app, SLOT(quit()));

    return app.exec();
}
0
source

Source: https://habr.com/ru/post/1793211/


All Articles