Qt5 Tutorial QThreads - Wait() - 2020
In this tutorial, we will learn about wait() function.
The main() starts with only the GUI thread running and it should terminate with only the GUI thread running. Exiting the program when another thread is still busy is a programming error, and therefore, wait() is called which blocks the calling thread until the run() method has completed.
bool QThread::wait(unsigned long time = ULONG_MAX)
The wait() blocks the thread until either of these conditions is met:
- The thread associated with this QThread object has finished execution (i.e. when it returns from run()). This function will return true if the thread has finished. It also returns true if the thread has not been started yet.
- time milliseconds has elapsed. If time is ULONG_MAX (the default), then the wait will never timeout (the thread must return from run()). This function will return false if the wait timed out.
This provides similar functionality to the POSIX pthread_join() function.
Starting from Qt Console Application, we need to create MyThread class.
We make the MyThread class get inherited from QThread.
Let's look at main.cpp:
#include <QCoreApplication> #include "mythread.h" #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); MyThread mThread; qDebug() << "GUI thread before MyThread start()" << app.thread()->currentThreadId(); mThread.start(); qDebug() << "GUI thread after start()" << app.thread()->currentThreadId(); mThread.wait(); qDebug() << "GUI thread after wait() " << app.thread()->currentThreadId(); return app.exec(); }
Let's look at mythread.h:
#ifndef MYTHREAD_H #define MYTHREAD_H #include <QThread> class MyThread : public QThread { Q_OBJECT public: explicit MyThread(QObject *parent = 0); void run(); signals: public slots: }; #endif // MYTHREAD_H
and mythread.cpp:
#include "mythread.h" #include <QDebug> MyThread::MyThread(QObject *parent) : QThread(parent) { } // We overrides the QThread's run() method here // run() will be called when a thread starts // the code will be shared by all threads void MyThread::run() { for(int i = 0; i <= 5; i++) { qDebug() << i; // slowdown the count change, msec this->msleep(500); } }
We can see the three threads are running simultaneously accessing the same code segment (i.e. run()):
GUI thread before MyThread start() 0x1944 GUI thread after start() 0x1944 0 1 2 3 4 5 GUI thread after wait() 0x1944
If we compare the result with the one that the line wait() is off:
GUI thread before MyThread start() 0xe4 GUI thread after start() 0xe4 GUI thread after wait() 0xe4 0 1 2 3 4 5
We can see "GUI thread after wait()" has been printed out not waiting for MyThread instance to finish.
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization