pause/contiune Workerfunc in Thread
-
Hello Guys,
i have a thread which calls a method in a cycle intervall:
void run() { while (true) { _holdOnMutex.lock(); if(!_holdOn) { doJob() ; /* my function which have to complete and has to blocks the thread_pause method */ } _holdOnMutex.unlock(); QThread::msleep(20); } }
now i want to pause and continue this thread in a conistent way, an wrote two mehtods:
QMutex _holdOnMutex; bool _holdOn; void pause_Thread() { _holdOnMutex.lock(); _holdOn = true; _holdOnMutex.unlock(); } void continue_Thread() { _holdOnMutex.lock(); _holdOn = false; _holdOnMutex.unlock(); }
is this a good approch, or there a better solution for my case?
Thank for your suggestions...:)
-
Hi,
QWaitCondition might be of interest.
-
I don't know if this is any better. But here's my pauseable_thread.py:
from PyQt5.QtCore import QThread, QMutex, QWaitCondition class PauseableThread(QThread): #(QThread): def __init__(self): super().__init__() self._pauseMutex = QMutex() self._pauseCond = QWaitCondition() self._paused = False def paused(self): return self._paused def pause(self): if self.isRunning() and not self._paused: self._pauseMutex.lock() self._paused = True self._pauseMutex.unlock() def resume(self): if self.isRunning() and self._paused: self._pauseMutex.lock() self._paused = False self._pauseMutex.unlock() self._pauseCond.wakeAll() def checkPause(self): self._pauseMutex.lock() if self._paused: self._pauseCond.wait(self._pauseMutex) self._pauseMutex.unlock()
You then inherit from this class and call
self.checkPause()
in your main thread loop or anywhere you deem appropriate. -
Thank for your replay, and thank for your QWaitCondition suggestion, but what i dont understand the mechansi in your pausable trhead class:
When call the pause method ,the paused flag is true,
the checkpause method rrun to the wait condion ,
the pausemutex is locked
how can the resume mothode execute, if the pausemutex is locked!?