views:

93

answers:

3

Hi, 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?

+4  A: 

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.

Georg
A: 

What Georg has said is correct. Also remember you can call signal slot from across threads. So you can have your threads emit a signal to you upon completion. SO you can keep track of no of threads that have completed their tasks/have exited. This could be useful if you don't want you Main thread to go in a blocking call wait.

Ankur Gupta
A: 

You can also use QWaitCondition

Kamil Klimek