QThread 总是卡在等待

问题描述

我正在尝试使用 QThread 调用一个线程中的函数,而无需冻结 UI。我在 windowslinux 上都使用 QT5.11.2

在 Windows 上一切正常,但 QThread 的 wait() 函数无论如何都不会返回。

我在 Linux 上使用 RHEL7

这是我正在做的:

void MainWidget::configure_click(double value)
{
    QThread *myThread = QThread::create([this,value]{ Configure(value); });
    dsoThread->setobjectName("My Configure Thread");
    QObject::connect(myThread,&QThread::finished,[](){ qDebug()<< "Configure Thread has finished";});  //  This is never printed

    myThread->start();
    myThread->wait();  //  Never returns from this
    myThread->quit();
    myThread->deleteLater();
}

我的 Configure 函数打印其开始和结束,并且这两行都在运行时打印

void MainWidget::Configure(double value)
{
    qDebug() << QThread::currentThread() << " started";
    
    //  Code to execute

    qDebug() << QThread::currentThread() << " finished";
}

我什至读到 quit() 会强制线程停止,所以只是为了测试,我尝试像这样切换 quit()wait()

    myThread->quit();
    myThread->wait();  //  Never returns from this either
    myThread->deleteLater();

我什至尝试循环 isRunning() 函数而不是 wait() 但我得到了相同的结果

    while(myThread->isRunning())  //  Same goes for !isFinished()
    {
        //  Do nothing
    }

似乎无论线程如何都不知道它已完成。

我能做些什么来解决这个问题或检查为什么会发生这种情况?

解决方法

  1. 您还没有start()编辑该线程。
  2. gui 线程中的
  3. myThread->wait(); 等待线程终止,因此它会阻塞 gui 线程事件循环,因此您会失去这种线程的所有好处,也可能只执行 Configure(value); 而不使用线程。

文档说:

wait() 和 sleep() 函数在 一般,因为 Qt 是一个事件驱动的框架。代替 等待(),考虑监听完成()信号。代替 sleep() 函数,考虑使用 QTimer。