使用 Qt/C++ 等待主线程中的所有线程完成

Wait until all threads are finished in main thread using Qt/C++

我想在代码中设置一个条件,等待主线程final slot中的所有线程完成,下面是测试代码..

testClass::testClass()
{
    m_count = 0;
    m_flag = false;
    for( int i = 0; i < 3; i++)
    {
        QThread *thread = new QThread();
        WorkerThread *worker = new WorkerThread();

        connect(thread, SIGNAL(started()), worker, SLOT(startThread()));
        connect(worker, SIGNAL(workerFinished()), this, SLOT(threadFinished()));
        connect(worker, SIGNAL(workerFinished()), thread, SLOT(quit()));
        connect(thread, SIGNAL(finished()), worker, SLOT(deleteLater()));
        connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
        thread->start();
        m_workerList.append(worker);
     }
}

void testClass::threadFinished()
{
    // wait untill all thread are finished, how to achive this ?
    if(!m_flag)
    {
        // print << m_flag;
        m_flag = true;
    }
}

void WorkerThread::startThread()
{
    emit workerFinished();
}

这里的 testClass 在主线程中,我希望应用程序在 threadFinished 槽中等待,直到我在 testClass 构造函数中启动的所有线程都完成,有人可以建议最好的方法吗?

我在 Windows 7.

中使用 Qt 5.4.0

如果除了 Qt 之外还可以使用 boost,您可以使用线程组并调用 join_all,等待组中的所有线程完成。

此外,QThreadPool 提供了 waitForDone() 函数 ("Waits for each thread to exit and removes all threads from the thread pool."),但是您可能需要稍微重构您的 worker 对象以符合 QRunnable 接口。

一个更基本的解决方案是为每个线程设置一个 QVector 或 QMap 成员变量,并在相应线程完成时将它们设置为 true。仅当所有线程都达到您的成员变量中的 "finished = true" 状态时,才继续在您的插槽中执行程序。