Python Terminate A Thread When It Is Sleeping
I modified the following code from first answer on this link. class StoppableThread(threading.Thread): '''Thread class with a stop() method. The thread itself has to check
Solution 1:
Your thread doesn't have to explicitly sleep
. It can simply wait for another thread to ask it to stop.
defrun(self):
while(not self._stop.isSet()):
self.awake.clear()
self._stop.wait(self._timeout) # instead of sleepingif self._stop.isSet():
continue
self.awake.set()
self._target()
For this purpose, you don't need the awake
event at all. (You might still need it if another thread wants to check its "status". I don't know if that's a requirement you have).
Without awake
, your code will be:
classStoppableThread(threading.Thread):
def__init__(self, target, timeout):
super(StoppableThread, self).__init__()
self._target = target
self._timeout = timeout
self._stop = threading.Event()
defrun(self):
whilenot self.stopped():
self._stop.wait(self._timeout) # instead of sleepingif self.stopped():
continue
self._target()
defstop(self):
self._stop.set()
defstopped(self):
return self._stop.isSet()
Post a Comment for "Python Terminate A Thread When It Is Sleeping"