QThread :: currentThread()vs QObject :: thread()

rzh*_*rov 2 c++ qt multithreading qthread qobject

我正在寻找答案,如果这两个函数之间有任何区别,除了第一个函数的常量:

QThread * QObject::thread() const
QThread * QThread::currentThread()
Run Code Online (Sandbox Code Playgroud)

Sin*_*all 9

他们是完全不同的.

QThread * QObject::thread() const返回特定QObject生活的线程.

QThread * QThread::currentThread() 返回指向QThread的指针,该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();
}
Run Code Online (Sandbox Code Playgroud)

样本输出:

当前线程是QThread(0x1436b20)
thread2地址是QThread(0x7fff29753a30)
对象在线程QThread(0x7fff29753a30)