2016-05-18 48 views
2

我無法找到任何明確的解決方案。我有一個以QtConcurrent::run()開頭的線程。在線程完成之前關閉應用程序時,應用程序崩潰。我希望應用程序在所有背景線程(QtConcurrent::run())完成後關閉。我該如何解決這個問題?Qt併發等待完成,當應用即將退出

+0

'QFuture 未來= QtConcurrent ::運行(yourFunction中);'然後你需要等待它完成:'future.waitForFinished();' – IAmInPLS

+0

ThaksAlexis.İf我用future.waitForFinished(),GUi被鎖定。這必須是後臺線程。當我接近應用程序,QtConcurrent :: run()必須完成 –

+0

然後,看看這個問題:http://stackoverflow.com/q/12527141/5653461和它的答案當然 – IAmInPLS

回答

0

我來到這裏尋找和你一樣的東西,並最終以我自己的方式解決它。這是我的方法:

// [...] All necessary includes would go here 

int main(int argc, char *argv[]) 
{ 
    // Keep track of time 
    quint64 start=QDateTime::currentMSecsSinceEpoch(); 

    // Qt app instance 
    QCoreApplication app(argc, argv); 

    // Someplace safe to keep our futures 
    QList<QFuture<void> > futures; 

    //Prepare the lambda that does the heavy lifting 
    auto lambda = [&] (void) { 
     // [...] Heavy lifting goes here 
    }; 

    // Run up some processing 
    for(/* any number of heavy liftings we need */){ 
     // Keep the returned future 
     auto future = QtConcurrent::run(lambda, /* parameters would go here*/); 
     // Store the future around for later 
     futures.append(future); 
    }; 

    //Now all the heavy lifting has started, and we are ready to wait for them all to complete. 
    for(auto future:futures){ 
     // Note that if the future finished BEFORE we call this, it will still work. 
     future.waitForFinished(); 
    } 

    // Spit out the number of seconds we were running 
    quint64 end=QDateTime::currentMSecsSinceEpoch(); 
    qDebug()<<"DONE after" <<(((qreal)end-start)/1000.0)<<" sec"; 

    //NOTICE: I did not need an event loop so no app.exec() call here 
}