I have an application on Qt with UI. And I want to do heavy calculations in the app. When I try to do this, my ui stops responding while doing complex calculations. I`m trying to implement multithreading by default lib. In another thread, I launched the function, but where I should write thread.join()? It turns out that I don't care that while the calculations are going on, the ui thread is blocked. Does anyone have a solution to this problem?
1 Answer
Qt is very full featured framework and there have been a lot of approach to handle thread. simple one is to use qtconcurrent module.
void myRunFunction(QString name)
{
for(int i = 0; i <= 5; i++)
{
qDebug() << name << " " << i <<
"from" << QThread::currentThread();
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFuture<void> t1 =
QtConcurrent::run(myRunFunction,
QString("A"));
QFuture<void> t2 =
QtConcurrent::run(myRunFunction,
QString("B"));
QFuture<void> t3 =
QtConcurrent::run(myRunFunction,
QString("C"));
t1.waitForFinished();
t2.waitForFinished();
t3.waitForFinished();
return a.exec();
}
Also you need to make sure add QT += concurrent in the qmake file and #include <QtConcurrent/QtConcurrent> in the cpp file that you are used of
where I should write thread.join()... nowhere, your GUI thread shouldn't wait on the worker threads, instead it should poll for the result every while if it is ready.std::thread. UseQThreadwith signals and slots. Or use any other mechanism from Qt framework, such asQRunnableorQtConcurrentmodule...