How to terminate a QThread + Worker process
-
Applying the same solution like in that example ( http://qt-project.org/wiki/QThreads_general_usage ), and assuming that the worker runs indefinitely, how can I elegantly implement the termination of the process.
For example:
@
void Worker::process()
{
for (int i = 0; i < 100000; i++)
{
qDebug() << i;
QThread::msleep(1000);
}
}
@When I start the thread, it starts counting, but neither quit(), nor terminate() can stop it.
-
Hi,
To stop the process() function, you need to call break; in your for-loop.
Anyway, QThread + Worker Object is for event-driven programming. Use it if you want to use signals and slots to communicate between threads.
However, a long for-loop (which is like an infinite loop) is incompatible with event-driven programming. quit() didn't work because it was waiting for your loop to finish running.
To run a long for-loop in a QThread, you should:
Subclass QThread.
DON'T use signals and slots with your QThread subclass.
Reimplement QThread::run() and put your loop inside it.
Check QThread::isInterruptionRequested() in your loop, and break if it returns true.
Call QThread::requestInterruption() to stop your thread.
@
class MyThread : public QThread {
...protected:
void run() {
for (int i = 0; i < 100000; i++) {
if (isInterruptionRequested())
break;
qDebug() << i;
QThread::msleep(1000);
}
}
};
@