2

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?

4
  • 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 Commented Apr 13, 2022 at 18:04
  • This question talks a little about several of the options: https://stackoverflow.com/questions/40284850/qthread-vs-stdthread Commented Apr 13, 2022 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. Commented Apr 13, 2022 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... Commented Apr 14, 2022 at 9:59

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.