如何在 qt 中从另一个线程运行 qt并发时关闭程序



我正在运行一个具有多线程的程序。该程序首先在其中运行一个主/UI线程。在这个程序中,我有一个工人和处理程序类。

工人类具有一个模拟函数,该函数仅生成随机数。模拟函数连续生成数字,而不会阻塞任何线程,即通过 Qtconcurrent。

从主/UI 线程中,我已将此 worker 类放入新线程中。处理程序类在主/UI 线程中运行,负责通过信号槽与在其他线程中运行的 worker 类进行通信。

到目前为止一切都很好。

当我尝试通过简单地单击应用程序十字按钮关闭程序时,问题就开始了。这 程序有点挂起它不关闭。但是,当我不将 worker 放在另一个类中并从同一个主/UI 线程运行 worker 类时,就没有问题并且程序以 0 退出。

所以我的问题是如何停止Qt并发是另一个线程,并最终关闭另一个线程

谢谢。

主.cpp

int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QThread l_newThread;
Worker* l_worker = new Worker();
handler * l_handler = new handler();
l_worker->moveToThread(&l_newThread);
QObject::connect(&l_newThread, &QThread::started, l_worker, &Worker::Init);
QObject::connect(l_handler,&handler::toStop_Signal,&l_newThread, &QThread::quit);
QObject::connect(l_worker, &Worker::toStop_Signal_Worker, l_handler,&handler::toStop_Slot);
QObject::connect(&app,&QCoreApplication::aboutToQuit, l_worker, &Worker::stop);
// QObject::connect(&app,&QCoreApplication::aboutToQuit, &l_newThread, &QThread::quit);
l_newThread.start();
// l_worker->Init();
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
int result = app.exec();
l_newThread.wait();
return result;
}

工人.cpp

#include "worker.h"
Worker::Worker(QObject *parent) : QObject(parent)
{
}
void Worker:: Init()
{
m_simulation = true;
simulate();
}
void Worker::simulate()
{
QtConcurrent::run([this]{
QRandomGenerator generator;
while (m_simulation) {

qint32 t = generator.bounded(0,100);
qDebug() << t;

qDebug() << "sleeping for 1 second";
QThread::sleep(1);
}
if (!m_simulation) {
qDebug() << "Killing the concurrent thread";
//  QThread::currentThread()->exit();
emit toStop_Signal_Worker();
}
});
}
void Worker::stop()
{
m_simulation = false;
}

处理程序.cpp

#include "handler.h"
handler::handler(QObject *parent) : QObject(parent)
{
}
void handler::toStop_Slot()
{
emit toStop_Signal();
}

结果

QML debugging is enabled. Only use this in a safe environment.
19
sleeping for 1 second
55
sleeping for 1 second
70
sleeping for 1 second
69
sleeping for 1 second
Killing the concurrent thread

这里可能发生的情况:toStop_Signal用于退出l_newThread的信号永远不会传递,因为当它发出时,事件循环已经死了并且消失了。因此,您的程序被卡在等待线程l_newThread.wait();.

我完全不完全明白你为什么要启动这个线程,只是为了在之后立即使用QtConcurrent::run并跨越另一个线程......

无论如何,一旦你确定你的工作线程已经停止(根据你发布的输出,你是(,你可以安全地直接在main中退出(基本上没用的(线程:

int result = app.exec();
l_newThread.exit(); //just quit it
l_newThread.wait();
return result;

然后你可以摆脱这个连接:

QObject::connect(l_handler,&handler::toStop_Signal,&l_newThread, &QThread::quit);

和(我猜(完全是处理程序。

最新更新