我正在寻找一个答案,是否存在这两个函数之间的差异,除了第一个函数的const性质以外:
QThread * QObject::thread() const
QThread * QThread::currentThread()
我正在寻找一个答案,是否存在这两个函数之间的差异,除了第一个函数的const性质以外:
QThread * QObject::thread() const
QThread * QThread::currentThread()
它们非常不同。
QObject::thread()
返回一个特定的 QObject
所在的线程。
QThread::currentThread()
返回一个指向当前正在执行的线程所管理的 QThread 的指针。
class MyClass : public QObject
{
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
MyClass * obj = new MyClass();
QThread thread2;
obj->moveToThread(&thread2);
thread2.start();
qDebug() << "The current thread is " << QThread::currentThread();
qDebug() << "The thread2 address is " << &thread2;
qDebug() << "The object is in thread " << obj->thread();
return app.exec();
}
示例输出:
当前线程是QThread(0x1436b20)
线程2的地址为QThread(0x7fff29753a30)
对象在线程QThread(0x7fff29753a30)中
它们有着不同的作用。
QThread::currentThread()
是一个静态函数,返回指向调用线程即当前线程的指针。
QObject::thread()
返回指向该对象所在的线程的指针。
虽然它们可能返回相同的结果,但它们并不相同。
第一个返回 QObject 所在的线程。
第二个返回当前正在执行的线程。