QThread::currentThread unexpected (at least for me…) behaviour
I was developing a complex application and I needed to know in a handler the id of the current running thread. I’m using Qt library. In QThread there is the static function QThread::currentThread returning a pointer to the current QThread (wooow!). Unfortunately it looks like to act in a different way I was expecting. The subsequent is a minimalistic Qt program using thread (not the original one).
- #include <QThread>
- #include <QtCore/QCoreApplication>
- #include <iostream>
- class MyThread : public QThread
- MyThread(QObject * parent = 0)
- std::cout << "thread addr (ctor) " << this << std::endl;
- void run()
- std::cout << "current thread addr (run) " << QThread::currentThread() << std::endl;
- int main(int argc, char *argv)
- QCoreApplication a(argc, argv);
- std::cout << "main thread addr " << qApp->thread() << std::endl;
- MyThread th;
- while (th.isRunning());
- return 0;
Running the program I get:
- main thread addr 009881D0
- thread addr (ctor) 0039F9A8
- current thread addr (run) 009881D0
So looks like that the current thread in the run function is the main thread!!! Probably I’m missing something important…Please, someone can help me and call me stupid? The static QThread::currentThread is too much important for what i’m writing…
PS I’m working with Qt 4.8 on visual studio 2008 in Win7 pc.
Of course it is, because you invoke run() from within the main thread. So looks like that the current thread in the run function is the main thread!
If you want to start a thread use start(), which then executes run() in a seperate thread.
And, as always when it comes to threading in Qt, make sure you’ve read Threads, Events and QObjects [qt-project.org] first.
Another important read on the correct use of QThreads is this one [qt-project.org]. Its not as extensive as the one suggested by Lukas Geyer but instead focuses on the (in my opinion) most important aspect related to the use of QThreads, namely the fact that they themself are not a thread but a wrapper around a thread object. And thus should be used this way.