Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait in the main thread until all worker threads have completed in Qt?

I have designed an application which is running 20 instance of a thread.

for(int i = 0;i<20;i++)
{
    threadObj[i].start();
}

How can I wait in the main thread until those 20 threads finish?

like image 234
Atul Avatar asked Feb 02 '10 06:02

Atul


1 Answers

You need to use QThread::wait().

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 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 till 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.

Just loop over the threads and call wait() for each one.

for(int i = 0;i < 20;i++)
{ 
    threadObj[i].wait(); 
}

If you want to let the main loop run while you're waiting. (E.g. to process events and avoid rendering the application unresponsible.) You can use the signals & slots of the threads. QThread's got a finished() singal which you can connect to a slot that remembers which threads have finished yet.

like image 96
Georg Schölly Avatar answered Oct 02 '22 12:10

Georg Schölly