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?
Asked
Active
Viewed 284 times
0
-
1***but where I should write thread.join()*** You don't want to add that in your GUI thread function as the GUI only updates when your function returns to the evenloop. You may want to have that in your destructor for your widget to ensure all threads you have started are finished. You may want to create your threads dynamically. You could consider using QThread. There are many ways to create and use multiple threads. There is also a QThreadPool – drescherjm Apr 13 '22 at 18:04
-
This question talks a little about several of the options: [https://stackoverflow.com/questions/40284850/qthread-vs-stdthread](https://stackoverflow.com/questions/40284850/qthread-vs-stdthread) – drescherjm Apr 13 '22 at 18:11
-
`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. – Ahmed AEK Apr 13 '22 at 19:48
-
Do not use `std::thread`. Use `QThread` with signals and slots. Or use any other mechanism from Qt framework, such as `QRunnable` or `QtConcurrent` module... – HiFile.app - best file manager Apr 14 '22 at 09:59
1 Answers
1
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

Ehsan Shavandi
- 132
- 7