Atul
Atul

Reputation: 51

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?

Upvotes: 5

Views: 14576

Answers (3)

Georg Sch&#246;lly
Georg Sch&#246;lly

Reputation: 126105

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.

Upvotes: 8

Ankur Gupta
Ankur Gupta

Reputation: 2300

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 your Main thread to go in a blocking call wait.

Upvotes: 1

Kamil Klimek
Kamil Klimek

Reputation: 13130

You can also use QWaitCondition

Upvotes: 2

Related Questions