信号/插槽多线程 Qt

Signal/slot multithreading Qt

本文关键字:Qt 多线程 插槽 信号      更新时间:2023-10-16

我知道这是关于线程之间连接信号/插槽机制的下一个问题。我写了工作工人应用程序。

主要问题

我有已移动到另一个线程的工人类。应用程序的第二部分是带有按钮的GUI界面。当我单击按钮线程启动时:

void MainWindow::startStopThreadA()
{
...
else
{
threadA = new QThread;
workerA = new WorkerObject;
workerA->setMessage("Thread A running");
workerA->moveToThread(threadA);
connect(threadA, SIGNAL(started()), workerA, SLOT(process()), Qt::QueuedConnection);
connect(workerA, SIGNAL(finished()), threadA, SLOT(quit()));
connect(workerA, SIGNAL(finished()), workerA, SLOT(deleteLater()));
connect(threadA, SIGNAL(finished()), threadA, SLOT(deleteLater()));
//Connect signal from thread with slot from MainWindow
connect(workerA, SIGNAL(printMessage(QString)), this, SLOT(printMessage(QString)), Qt::QueuedConnection);
threadA->start();
ui->threadAButton->setText("Stop A");
}
}

当线程启动时,发出信号:

void WorkerObject::process(void)
{
//Infinity thread loop
forever
{
//Exit loop part
mutex.lock();
if(m_stop)
{
m_stop = false;
mutex.unlock();
break;
}
mutex.unlock();
//Hold/unhold loop part
mutex.lock();
if(!m_hold)
{
mutex.unlock();
//Here signal is emited
emit printMessage(messageStr);          //That not works
//qDebug() << "Thread A test message."; //That works properly
}
mutex.unlock();
}
emit finished();
}

在主 GUI 线程中,我有计时器来显示 GUI 线程工作。所以qDebug()工作正常并从我的线程打印消息。来自 GUI 线程的计时器也可以正常工作textEdit并在 GUI 字段中打印消息。

现在,当发出printMessage信号时,GUI 线程执行插槽方法:

void MainWindow::printMessage(QString str)
{
ui->textEdit->append(str);
}

这是我问题中最重要的部分:

当来自workerA对象的信号printMessage与 GUI 插槽连接时printMessageQt::QueuedConnection我的应用程序挂起。无法单击某些按钮甚至退出应用程序。

当信号/插槽与Qt::BlockingQueuedConnection连接时,一切正常。消息在线程之间发出和接收,GUI 计时器工作正常。

所以我的问题是为什么连接Qt::QueuedConnection会导致应用程序冻结?

我在@m7913d的帮助下解决了这个问题。

您可以尝试在永久循环中执行QThread::sleep(例如 1 秒(以检查它是否解决了您的问题。

所以工人的线程发出信号太频繁了。在发出信号后添加QThread::msleep(5)确实有帮助。还需要包括 '。