Created a QThread in main() i.e Main thread. Moved a worker class to the new thread. The thread executes the \'StartThread\' method of worker class.
Worker Thread:>
You seem to have many misconceptions.
From the Qt docs, both QThread::quit() and QThread::exit():
Tell the thread's event loop to exit
That means that if the thread's event loop is not running (either QThread::exec() have not been called or the event loop busy executing some heavy blocking function(like your StartThread
)) , the thread will not quit until the control is back into the event loop. I think that explains why quit()
and exit()
did not work for you as expected.
Also you seem to be using QThread::requestInterruption()
in a wrong way, back to the Qt docs:
Request the interruption of the thread. That request is advisory and it is up to code running on the thread to decide if and how it should act upon such request. This function does not stop any event loop running on the thread and does not terminate it in any way.
so this does not really do any thing with your thread, it just causes subsequent calls to QThread::isInterruptionRequested() to return true
, so that when you detect that (within the thread) you should perform clean-up and quit as soon as possible (again in order for quit()
to work here, the event loop should be running, so you should return from your StartThread
function here, to get the thread back into its event loop again).
Now to answer your question:
Is it possible to stop/dispose the thread as in when required by the main thread?
To do that, you should either avoid such long running functions and make sure you return to the event loop as soon as possible, so that quit()
/exit()
can work. Or perform clean-up and return from the current function as soon as you detect that isInterruptionRequested()
is returning true, so that calls to quit()
/exit()
can work after that.
As pointed out by @kuba you may choose to use a thread pool instead of managing your thread's life manually.
P.S. you don't have to store a pointer to your QThread
inside the Worker
in order to use isInterruptionRequested()
. you can use QThread::currentThread()->isInterruptionRequested()
instead of m_pCurrentThread->isInterruptionRequested()
(the same thing applies to your exit call m_pCurrentThread->isInterruptionRequested()
)