[英]Qt, C++, How to Quit QThread
我有一個計算器和要放在QThread上的計算器方法startCalculations()。 我成功連接了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文檔規范 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.