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

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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top