QThread::currentThread () vs QObject::thread()
Asked Answered
B

3

5

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()
Bordereau answered 22/10, 2015 at 12:7 Comment(0)
P
11

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)

Precedent answered 22/10, 2015 at 12:14 Comment(0)
G
4

They do two different things. QThread::currentThread() is a static function that returns a pointer to the thread which it is called from, ie. current thread.

QObject::thread() returns a pointer to the thread in which this object lives in.

Gnarly answered 22/10, 2015 at 12:12 Comment(0)
I
1

They are not the same although they might return the same result.

1st one returns the thread that the QObject lives in.

2nd one returns the currently executing thread.

Irk answered 22/10, 2015 at 12:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.