Remove scheduled thread from QThreadPool
-
Hi,
is it possible to remove a thread which is scheduled through QConcurrent::run for running from the schedule i. e. something happened in one of the threads currently running and now I want to stop all other threads because I don't need their results any more.
Thanks,
butterface -
Why not simply define an abort flag and give each thread a pointer to that flag in the constructor? The thread would then check the flag in its run() method before it starts work (and maybe also periodically). If the flag has been set for whatever reason, the thread will abort ASAP. At least that's what I do ;-)
@volatile bool globalAbortFlag = false;
void startJobs(void)
{
globalAbortFlag = false;
while(moreJobsAvailable)
{
m_threadPool.start(new MyTask(&globalAbortFlag));
}
)void abortJobs(void)
{
globalAbortFlag = true;
m_threadPool.waitForDone();
}//----------
class MyTask : public QRunnable
{
public:
MyTask(volatile bool *abortFlag)
{
m_abortFlag = abortFlag;
}virtual void run(void) { while(!jobCompleted) { if(*m_aborted) return; perfromNextStep(); } }
private:
volatile bool *m_aborted;
}
@ -
Okay that sounds appropriate. But there is no other way to remove them?
-
By looking at the QThreadPool documentation:
NoAnd it's also clear why: How should the ThreadPool be able to abort a job once it is running? If that job has no special function/flag to abort the job - and QRunnable has no such such API - only the entire thread could be terminated. Killing a thread always comes at the danger of leaving resources in an undefined state (resource leak an other evil things).
Well, at least jobs not started yet could be discarded (descheduled), using some removeAllPendingJobs() function. But maybe these jobs should never have be scheduled instead of removing them again. In general you have to assume that a job might be started immediately, once it has been added.