我有一个计算器和一个计算器方法 startCalculations() ,它被放到一个 QThread 上。我成功连接了 mStopCalcButton 和线程的 quit()/terminate()。但是,当我按下 mStopCalcButton 时,线程不会退出/终止。
这是有问题的代码...
mStopCalcButton->setEnabled(true);
QThread* thread = new QThread;
Calculator* calculator = new Calculator();
calculator->moveToThread(thread);
connect(thread, SIGNAL(started()), calculator, SLOT(startCalculations())); //when thread starts, call startCalcuations
connect(calculator, SIGNAL(finished()), thread, SLOT(quit()));
connect(calculator, SIGNAL(finished()), calculator, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
connect(mStopCalcButton, SIGNAL(released()), thread, SLOT(quit()) );
在计算器中,这是唯一定义的方法...
void Calculator::startCalcuations()
{
int x = 0;
while (true)
qDebug() << x++;
}
为什么我的 QThread 没有退出?
最佳答案
首先,函数 QThread::quit() 只告诉该线程退出它的事件循环,但不做任何与终止或退出相关的事情。你可以在这里阅读 Qt 文档:QThread:quit()
要终止线程,一般来说,您应该使用停止标志而不是无限循环来更改线程的运行函数代码。每当你想终止线程时,你只需要改变那个停止标志并等待线程终止。
使用停止标志:
void Calculator::startCalcuations()
{
int x = 0;
while (!mStopFlag) {
qDebug() << x++;
// In addition, you should add a little sleep here to avoid CPU overhelming
// like as msleep(100);
}
}
通过打开停止标志来终止线程:
void YourClass::requestTerminateThread()
{
mStopFlag = true;
if(!thread.wait(500))
{
thread.terminate(); // tell OS to terminate thread
thread.wait(); // because thread may not be immediately terminated by OS policies
}
}
此外,正如您看到我对上述代码的评论,您应该添加一些线程休眠时间以避免 CPU 重载。
更多信息,请清楚阅读QThread document specs首先。
关于c++ - Qt, C++, 如何退出 QThread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47320417/