信号/插槽多线程 Qt
Signal/slot multithreading Qt
我知道这是关于线程之间连接信号/插槽机制的下一个问题。我写了工作工人应用程序。
主要问题
我有已移动到另一个线程的工人类。应用程序的第二部分是带有按钮的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 插槽连接时printMessage
与Qt::QueuedConnection
我的应用程序挂起。无法单击某些按钮甚至退出应用程序。
当信号/插槽与Qt::BlockingQueuedConnection
连接时,一切正常。消息在线程之间发出和接收,GUI 计时器工作正常。
所以我的问题是为什么连接Qt::QueuedConnection
会导致应用程序冻结?
我在@m7913d的帮助下解决了这个问题。
您可以尝试在永久循环中执行QThread::sleep(例如 1 秒(以检查它是否解决了您的问题。
所以工人的线程发出信号太频繁了。在发出信号后添加QThread::msleep(5)
确实有帮助。还需要包括 '。
相关文章:
- 将对象传递给多线程对象 Qt
- Qt::D irectConnection在多线程环境中使用时如何工作?
- 带GUI的Qt多线程
- Qt多线程:如何更新两个QLabel?
- 信号/插槽多线程 Qt
- QT脚本多线程
- 带有QT OpenCV的多线程
- 多线程会导致 Qt 中的运行时错误
- Qt中的多线程通信
- QT插槽未在多线程DLL中执行
- 如何使用QT/C 中的多线程用API访问我的数据库
- Qt多线程启动线程错误
- Qt多线程通信
- qt多线程:计算一个积分
- 由于删除c++Qt多线程应用程序中的指针而导致崩溃
- Qt多线程电子邮件:QObject:无法为处于不同线程中的父级创建子级
- Qt多线程项目-调试器冻结
- 使用VTK和QT多线程时访问冲突异常
- Qt:多线程连接不工作
- QT多线程和移动对象线程创建后