I'm trying to understand a highly-upvoted solution to the problem of killing a thread in Python: Is there any way to kill a Thread in Python?. The author provides a class StoppableThread
and describes in words how to use it (namely, by calling its stop()
method and waiting for the thread to exit properly using join()
).
I've tried to make this work using a simple example:
import time
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stop = threading.Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
def run_forever():
while True:
print("Hello, world!")
time.sleep(1)
thread = StoppableThread(target=run_forever)
thread.start()
time.sleep(5)
thread.stop()
thread.join()
I would expect the program to print Hello, world!
approximately 5 times before the thread
is stopped. However, what I observe is that it just keeps on printing indefinitely.
Can someone clarify the correct usage of the StoppableThread
subclass?