简体   繁体   中英

Qt C++ how stop thread if moveToThread

After lots of experimentation and learning from stackoverflow, I've create a QObject worker, a QThread, and moved my QObject worker to my QThread, and started the QThread - and it's working!

void TelnetServer::incomingConnection(qintptr socketDescriptor)
{
    QThread * TelnetConnectionThread = new QThread(this);
    TelnetConnection *worker = new TelnetConnection(socketDescriptor,TelnetConnectionThread);
    connect(TelnetConnectionThread, SIGNAL(started()), worker, SLOT(start()));
    connect(TelnetConnectionThread, SIGNAL(finished()), worker, SLOT(deleteLater()));
    worker->moveToThread(TelnetConnectionThread);
    TelnetConnectionThread->start();  // Start the thread running
}

I assume that calling TelnetConnectionThread->start() starts the eventloop within the QThread (since it seems to be running). Now the problem...how do I stop the thread? I tried:

QThread::quit();

but the thread is still running when I shutdown the app. Does this mean the exec loop is not running? Do I have to do something else to stop this thread? Or is it actually stopped but just not deleted?

It's a bad idea to kill running thread, from design and technical points of view. Usually the thread must own the decision to quit based on "terminate" flag. For example create new flag "stop", if quit() slot is signaled mark the flag true. In a thread function verify the flag periodically and if it's true - exit thread function.

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