Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am looking for an answer if there is any difference between these two functions, aside from the constness of the first one:

QThread * QObject::thread() const
QThread * QThread::currentThread()
like image 795
rzhurov Avatar asked Dec 06 '22 20:12

rzhurov


1 Answers

They are quite different.

QThread * QObject::thread() const returns the thread in which a particular QObject lives.

QThread * QThread::currentThread() Returns a pointer to a QThread which manages the currently executing thread.

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();
}

Sample output:

The current thread is QThread(0x1436b20)
The thread2 address is QThread(0x7fff29753a30)
The object is in thread QThread(0x7fff29753a30)

like image 123
SingerOfTheFall Avatar answered Dec 22 '22 13:12

SingerOfTheFall