我正在运行一个具有多线程的程序。该程序首先在其中运行一个主/ UI线程。在此程序中,我有一个worker和handler类。
worker类具有一个模拟函数,该函数仅生成随机数。模拟功能连续生成数字而不会阻塞任何线程,即通过Qtconcurrent。
从main / UI线程中,我已将此工作类放入新线程中。处理程序类在主/ UI线程中运行,并负责通过信号插槽与在其他线程中运行的工作程序类进行通信。
到目前为止,一切正常。
当我尝试通过单击应用程序交叉按钮来关闭程序时,问题开始。 程序挂起它不会关闭。但是,当我不将worker放在另一个类中并从同一主/ UI线程运行worker类时,就没有问题,程序会以0退出。
所以我的问题是如何停止Qtconcurrent是另一个线程并最终也关闭另一个线程。
谢谢。
main.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;
}
worker.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;
}
handler.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);
和(我猜想是全部)处理程序。