本篇介绍详细了解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与跨线程信号槽的内容介绍完了,希望本文对你有所帮助!