NDestiny
NDestiny

Reputation: 1191

Wait till all the Qt concurrent threads finished

I am running 5 threads as below

for(int i=0; i< 5 ; i++
{
   QtConcurrent::run()
}

I want to wait here till all the threads get finished.

void QFutureSynchronizer::waitForFinished ()  is hanging my main GUI.

So I want to use some thing like this QEventLoop::exec();

But how to exit out of this exec() once all the results available?

Edited: - I did some thing like this, that works for me

constructor()
{
   m_noOfThreadsFinished = 0;
   m_totalThreads = 5;

    for(int i=0; i< 5 ; i++
    {
       QFuture<void> l_future =  QtConcurrent::run();
       QPointer< QFutureWatcher<void> >  l_futurewatcher = new  QFutureWatcher<void>();
        connect(l_futurewatcher, SIGNAL(finished()), this, SLOT(FinishedThread()) );
        l_futurewatcher->setFuture(l_future);    
    }

    if(eventLoop != NUL)
          delete eventLoop;
    eventLoop = new QEventLoop(); // QPointer<QEventLoop> eventLoop; is class member

     //start event loop here, so that GUI wont block
     eventLoop->ecec(); 

    //do things after all threads finished
}

void FinishedThread() //slot 
{
    QFutureWatcher<void>* l_futurewatcher = static_cast< QFutureWatcher<void>* > (sender());
    l_futurewatcher->deleteLater();

   if( (++m_noOfThreadsFinished == m_totalThreads) && !m_processCancelled)
   {
        emit finishedreading();
   }
}

void FinishedAllThreads() //slot for finishedreading 
{
    killLocalEventLoop();
}

void killLocalEventLoop()
{
  //QPointer automatically make eventLoop to NULL, when it got deleted 
  eventLoop->quit();
  eventLoop->deleteLater();
}

NOTE : you people can ask why cann't I do the things in FinishedThread() slot when I get to know all threads are finished, project I am working in forcing me to do the things in constructor only when all threads finished(This may not be situation for you then you can do things in FinishedThread() slot).

Upvotes: 0

Views: 2750

Answers (1)

The solution is quite simple: don't ever use any waitForXxx methods in Qt. They are never necessary.

Instead, you should be connecting to the QFutureWatcher::finished() signal. See, for example, this answer.

For some other reason I can not use QFutureWatcher() to get to know all the finished results.

There's no such reason.

Upvotes: 2

Related Questions