詳細(xì)了解Thread Affinity與跨線程信號(hào)槽
本篇介紹詳細(xì)了解Thread Affinity與跨線程信號(hào)槽,QObject的線程依附性(thread affinity)是指某個(gè)對(duì)象的生命周期依附的線程(該對(duì)象生存在該線程里)。我們?cè)谌魏螘r(shí)間都可以通過(guò)調(diào)用QObject::thread()來(lái)查詢線程依附性,它適用于構(gòu)建在QThread對(duì)象構(gòu)造函數(shù)的對(duì)象。
- // 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();
 - }
 
打印結(jié)果:
- Debugging starts
 - mainThread QThread(0x3e2870)
 - thread QThread(0x3e2870)
 - Object QThread(0x3e2870)
 - run Thread(0x22ff1c)
 - aSlot QThread(0x3e2870)
 - aSlot called
 
我們知道跨線程的信號(hào)槽連接需要使用queued connection, 上述代碼中QObject::connect(&thread, SIGNAL(aSignal()), &obj, SLOT(aSlot())); 雖然thread與obj的線程依附性相同,它們都隸屬于 地址為0x3e2870的線程; 但是我們看到發(fā)射aSignal的線程
與之不同是0x22ff1c. 這就是為什么使用queued connection。
小結(jié):關(guān)于詳細(xì)了解Thread Affinity與跨線程信號(hào)槽的內(nèi)容介紹完了,希望本文對(duì)你有所幫助!















 
 
 



 
 
 
 