开发者

Questions about QThread

If I make a QThread and call one of its slots from another thread, will it be called in the context of the thr开发者_运维知识库ead of the QThread object, or from the context of the thread which made the call?


If you execute the slot by emitting a signal, then it depends on the type of signal-to-slot connection you have. A slot connected to a signal via a direct connection would execute in the emitter's thread. A slot connected via a queued connection would execute in the receiver's thread. Please see here: http://doc.qt.nokia.com/4.7/threads-qobject.html

If the slot is executed directly, with [QThread object]->slot(), then the slot will execute in the thread that makes the call.


Direct calls are always executed in the context of the calling thread.


A slot called by a signal will run in the thread for which the QObject is associated. A slot called directly will run in the current thread. Here is a test program which demonstrates.

Output:

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

Test 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜