PDA

View Full Version : How to stop QThread?



vespasianvs
14th March 2010, 01:42
Hi, this problem might sound weird, but it got me crazy:mad: as I just started using QThread. Here is a short program to test using QThread.



#include <QThread>
#include <QCoreApplication>
#include <QDebug>

int main (int argc, char** argv) {
QCoreApplication app(argc, argv);
QThread t;
t.start();
if (t.isRunning())
qDebug() << "thread is started";
//t.exit();
//t.quit();
t.terminate();
qDebug() << "try to stop thread";
if(!t.isRunning())
qDebug() << "thread is stopped";
return app.exec();
}


I tried exit(), quit() and terminate() and waited for a long time.
The expected "thread is stopped" never ever shows up (no matter how long I waited). The thread is like running forever. Could anyone help me with this and show me how to properly stop a QThread?

Thank you.

Ves

norobro
14th March 2010, 04:26
Re: QThread::quit() & exit() - From the docs:
This function does nothing if the thread does not have an event loop.
As for "thread is stopped" you need a delay before "if(!t.isRunning())". See QThread::wait(). Or you could put in a while statement which is essentially what wait() does:
t.terminate();
qDebug() << "try to stop thread";

while(!t.isFinished()){}

if(!t.isRunning())
qDebug() << "thread is stopped";

HTH

vespasianvs
14th March 2010, 05:33
I got it. At least, terminate() can stop the eventloop inside the run(). I am wondering if there is a way actually KILL a Qthread, or it is completely up to the OS to do it. :confused:

Thanks

toutarrive
14th March 2010, 06:42
Accordind to Qt doc:

To stop a thread:

Execution ends when you return from run(), just as an application does when it leaves main()
Concerning terminate():

Warning: This function is dangerous and its use is discouraged. The thread can be terminate at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to cleanup after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.

So you can use a flag inside the run() function when you want to make it stop.
You set this flag from outside the thread that is checked by the computation within the thread and stop the calculation if the flag is set.



void myThread::run()
{
while (! isThreadstopped)
{
// do your threaded stuff;
}

} // thread has terminated.