什么是QThread C ++中的std :: thread :: join等效项

问题描述

如何等待QThread的完成或std::thread::join()中的QThread方法的等效方式

在std :: thread中,我可以像下面这样


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";
}

输出给出以下输出

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

解决方法

谢谢@ Alex F的建议。

这是我当时尝试的:

#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,[](){ qDebug()<< "Thread2 has finished";});

 

    thread1->start();

    thread2->start();

 

    qDebug()<< "Waiting for threads to finish";

    thread1->wait();

    thread2->wait();

 

    qDebug() << "done";

 

    return a.exec();

}

输出如下:

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