詳細了解Thread Affinity與跨線程信號槽
本篇介紹詳細了解Thread Affinity與跨線程信號槽,QObject的線程依附性(thread affinity)是指某個對象的生命周期依附的線程(該對象生存在該線程里)。我們在任何時間都可以通過調用QObject::thread()來查詢線程依附性,它適用于構建在QThread對象構造函數的對象。
- // file multiSignal.h
- #ifndef MULTISIGNAL_H
- #define MULTISIGNAL_H
- #include <QThread>
- class Thread : public QThread
- {
- Q_OBJECT
- signals:
- void aSignal();
- protected:
- void run();
- };
- class Object: public QObject
- {
- Q_OBJECT
- public slots:
- void aSlot();
- };
- #endif // MULTISIGNAL_H
- // file multiSignal.h
- #ifndef MULTISIGNAL_H
- #define MULTISIGNAL_H
- #include <QThread>
- class Thread : public QThread
- {
- Q_OBJECT
- signals:
- void aSignal();
- protected:
- void run();
- };
- class Object: public QObject
- {
- Q_OBJECT
- public slots:
- void aSlot();
- };
- #endif // MULTISIGNAL_H
- view plaincopy to clipboardprint?
- #include <QtCore/QCoreApplication>
- #include <QDebug>
- #include <QTimer>
- #include "multiSignal.h"
- void Object::aSlot()
- {
- QTimer *timer = new QTimer;
- qDebug()<< "aSlot " << timer->thread();
- qDebug() << "aSlot called";
- delete timer;
- }
- void Thread::run()
- {
- QTimer *timer = new QTimer;
- qDebug()<< "run " << timer->thread();
- emit aSignal();
- delete timer;
- }
- int main(int argc, char *argv[])
- {
- QCoreApplication a(argc, argv);
- Thread thread;
- Object obj;
- qDebug()<< "mainThread " << a.thread();
- qDebug()<< "thread " << thread.thread();
- qDebug()<< "Object " << obj.thread();
- QObject::connect(&thread, SIGNAL(aSignal()), &obj, SLOT(aSlot()));
- thread.start();
- return a.exec();
- }
- #include <QtCore/QCoreApplication>
- #include <QDebug>
- #include <QTimer>
- #include "multiSignal.h"
- void Object::aSlot()
- {
- QTimer *timer = new QTimer;
- qDebug()<< "aSlot " << timer->thread();
- qDebug() << "aSlot called";
- delete timer;
- }
- void Thread::run()
- {
- QTimer *timer = new QTimer;
- qDebug()<< "run " << timer->thread();
- emit aSignal();
- delete timer;
- }
- int main(int argc, char *argv[])
- {
- QCoreApplication a(argc, argv);
- Thread thread;
- Object obj;
- qDebug()<< "mainThread " << a.thread();
- qDebug()<< "thread " << thread.thread();
- qDebug()<< "Object " << obj.thread();
- QObject::connect(&thread, SIGNAL(aSignal()), &obj, SLOT(aSlot()));
- thread.start();
- return a.exec();
- }
打印結果:
- Debugging starts
- mainThread QThread(0x3e2870)
- thread QThread(0x3e2870)
- Object QThread(0x3e2870)
- run Thread(0x22ff1c)
- aSlot QThread(0x3e2870)
- aSlot called
我們知道跨線程的信號槽連接需要使用queued connection, 上述代碼中QObject::connect(&thread, SIGNAL(aSignal()), &obj, SLOT(aSlot())); 雖然thread與obj的線程依附性相同,它們都隸屬于 地址為0x3e2870的線程; 但是我們看到發射aSignal的線程
與之不同是0x22ff1c. 這就是為什么使用queued connection。
小結:關于詳細了解Thread Affinity與跨線程信號槽的內容介紹完了,希望本文對你有所幫助!