I have been trying to provide the functionality to stop a thread following this thread . I have the following class:
class WorkerThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, id):
super(WorkerThread, self).__init__()
self._id = id
self._stop = threading.Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
def run(self):
while not self.stopped():
print ("Thread with id {0} Running".format(self._id))
time.sleep(1)
When I create 10 threads and try to stop them, none of them stop and keep printing.
threads = [WorkerThread(x) for x in range(10)]
[thread.start() for thread in threads]
time.sleep(2) #wait
[thread.stop() for thread in threads]
[thread.join() for thread in threads]
print "All done" #never printed
Can someone explain why the stop event is ignored? I also tried using the _stop
attribute as a flag and setting it to false in __init__
and True
in stop()
with no luck.