Making the main thread wait till all other Qthread finished

Well, what about:

a.wait();
b.wait();

Or, you would rather start an event loop (as usually for Qt applications) that you quit when both of your threads end (QThread emits finished() and terminated() signals).


Normally, with Qt you will have a QApplication based class with an event loop with signals and slots, that will not exit from the main function until you want to. In that case you can simply connect the QThread::finish() signal to a slot that checks if all threads are done.

Without an event loop and signals/slots, Qt threads don't have a join() method, found in other threading implementation, but QThread::wait() is somewhat similar.

bool QThread::wait(unsigned long time = ULONG_MAX)

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 QThread::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 QThread::run()). This function will return false if the wait timed out.

Note tho that it is considered a terrible practice to block the main thread, not even with computation, much less just to wait for something. Anything over several dozen milliseconds has detrimental effect on the user experience, and higher stalls are likely to give you a "this app is not responding" msg from the OS. If you wait on a result, wait for it in another thread, and only pass it to the main thread once it is done.

Tags:

C++

Qthread