简体   繁体   中英

Qt, C++, How to Quit QThread

I have a calculator and a calculator method startCalculations() which is to put onto a QThread. I successfully connect mStopCalcButton and the thread's quit()/terminate(). However, when I press mStopCalcButton, the thread does not quit/terminate.

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?

The first thing, function QThread::quit() only tell that thread to exit it's event loop, but do nothing related to terminate or exit. you can read Qt document here: 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.

For more information, please clearly read QThread document specs first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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