is there a way to force the main thread to wait until all threads created from it, will finish their job, before finishing the program. I mean:
int main(){
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 fromQThread::run()
). This function will returntrue
if the thread has finished. It also returnstrue
if the thread has not been started yet.time
milliseconds has elapsed. If time isULONG_MAX
(the default), then the wait will never timeout (the thread must return fromQThread::run()
). This function will returnfalse
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.