简体   繁体   English

Qt,C ++,如何退出QThread

[英]Qt, C++, How to Quit QThread

I have a calculator and a calculator method startCalculations() which is to put onto a QThread. 我有一个计算器和要放在QThread上的计算器方法startCalculations()。 I successfully connect mStopCalcButton and the thread's quit()/terminate(). 我成功连接了mStopCalcButton和线程的quit()/ terminate()。 However, when I press mStopCalcButton, the thread does not quit/terminate. 但是,当我按mStopCalcButton时,线程不会退出/终止。

Here is the code in question... 这是有问题的代码...

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()) );

In the calculator, this is the only defined method... 在计算器中,这是唯一定义的方法...

void Calculator::startCalcuations()
{
    int x = 0;
    while (true) 
        qDebug() << x++;    
}

Why does my QThread not quit? 为什么我的QThread不退出?

The first thing, function QThread::quit() only tell that thread to exit it's event loop, but do nothing related to terminate or exit. 首先,函数QThread :: quit()仅告诉该线程退出事件循环,但不执行任何与终止或退出相关的操作。 you can read Qt document here: QThread:quit() 您可以在这里阅读Qt文档: QThread:quit()

To terminate a thread, in general implement, you should change your thread's running function code by using stop flag rather than infinitive loop. 要终止线程,一般来说,应该使用停止标志而不是无限循环来更改线程的运行功能代码。 Whenever you want to terminate thread, you only need change that stop flag and wait for thread terminating. 每当您要终止线程时,您只需要更改该停止标志并等待线程终止即可。

Using stop flag: 使用停止标志:

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);
    }
}

Terminate thread by turning on the stop flag: 通过打开停止标志来终止线程:

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
    }
}

In addition, as you can see my comment on above code, you should add some thread sleep time to avoid CPU overhelming. 另外,如您在上面的代码中看到的我的评论一样,您应该增加一些线程睡眠时间,以避免CPU负担过多。

For more information, please clearly read QThread document specs first. 有关更多信息,请首先清楚地阅读QThread文档规范

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM