Search code examples
c++c++11qt5qthreadstdthread

What is the equivalent of std::thread::join in QThread C++


How can I wait for the finish of a QThread or What is the equivalent of std::thread::join() method in QThread

In std::thread, I can do it like the following


void foo()
{
    // simulate expensive operation
    std::cout << "starting first thread1...\n";
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

void bar()
{
    // simulate expensive operation
    std::cout << "starting second thread2...\n";
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main()
{

    std::thread thread1(foo);


    std::thread thread2(bar);

    
    std::cout << "waiting for threads to finish..." << std::endl;
    thread1.join();
    thread2.join();

    std::cout << "done!\n";
}

The output gives the following output:

starting first thread1...
waiting for threads to finish...
starting second thread2...
done!

Solution

  • Thank you @Alex F for your suggestion.

    Here is what I tried then:

    #include <QApplication>
    
    #include <QThread>
    
    #include "mydialog.h"
    
    #include <QDebug>
    
     
    
    void foo()
    
    {
    
        // simulkate a long work
    
        qDebug() << " Starting Qthread1 ..." ;
    
        QThread::msleep(5000);
    
    }
    
     
    
    void bar()
    
    {
    
        qDebug() << " Starting Qthread2 ..." ;
    
        QThread::msleep(2000);
    
    }
    
     
    
     
    
    int main(int argc, char *argv[])
    
    {
    
        QApplication a(argc, argv);
    
     
    
        QThread* thread1 = QThread::create(foo);
    
        QThread* thread2 = QThread::create(bar);
    
     
    
        // to verify at real-time when the thread finishes
    
        QObject::connect(thread1, &QThread::finished, [](){ qDebug()<< "Thread1 has finished";});
    
        QObject::connect(thread2, &QThread::finished, [](){ qDebug()<< "Thread2 has finished";});
    
     
    
        thread1->start();
    
        thread2->start();
    
     
    
        qDebug()<< "Waiting for threads to finish";
    
        thread1->wait();
    
        thread2->wait();
    
     
    
        qDebug() << "done";
    
     
    
        return a.exec();
    
    }
    

    The output is as follows:

    Waiting for threads to finish
      Starting QThread2 ...
      Strating QThread1 ...
    Thread 2 has finished 
    Thread 1 has finished