Qt,C ++,如何退出QThread

时间:2017-11-16 02:10:23

标签: c++ multithreading qt qthread

我有一个计算器和一个计算器方法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不会退出?

1 个答案:

答案 0 :(得分:3)

首先,函数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

相关问题