Terminating QThread properly
-
Hello,
I have a multithread application and what I basically want is to kill a thread during its run by sending it a signal from another QObject.
I have simplifed the code like bellow :The output given is :
Going for sleep Worker(0x193cfb0)
Waiking up
Going for sleep Worker(0x193cfb0)
Killing thread QThread(0x193ad00)
Waiking up
Going for sleep Worker(0x193cfb0)
Waiking up
Going for sleep Worker(0x193cfb0)
Waiking up
Going for sleep Worker(0x193cfb0)
Waiking upThe problem I have is that the thread is not really killed exactly when the signal is sent ... I know I can use terminate() but its not recommended and it is too abrupt (in my application before terminate the thread I would like to do some operations then emit a result). I could also use requestInterruption() and add in the worker for loop an isInterruptionRequest but I want to kill the blocking operation if any is running (here its a sleep but it could be a wait on QNetworkAccessManager request).
I would like to know if there is any way to do what I want to do ?
-
@Narveth
How about put a stop flag in run()?
As a member variable of Worker class, definebool stop; ... stop = false; void stopThread() {stop = true;} ... for(int i=0;i<5;++i){ if(stop){ Do whatever you want. break; } ... }
And you can stop thread by
running stopThread(). -
Thanks for the reply,
But as I said I would like to stop the current operation the thread is actually doing. So imagine instead of Qthread::sleep(5) I have QThread::sleep(500000) and the signal is sent right after the sleep has begun, my thread will stop after the sleep and not during. I would like to interrupt the sleep and I dont know if its possible.
-
Hi,
If you have to sleep such a long time then you might not be using the right technology to handle such a wait. A QWaitCondition might be more suited.