Skip to content

Instantly share code, notes, and snippets.

@tsibley
Created November 21, 2023 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsibley/a3ef81f9006766853ac61287c05e644d to your computer and use it in GitHub Desktop.
Save tsibley/a3ef81f9006766853ac61287c05e644d to your computer and use it in GitHub Desktop.
"""
Threading utilities.
"""
from threading import Thread, Event
class StoppableThread(Thread):
"""
A :cls:`Thread` with a :meth:`.stop` function and :attr:`.stopped`
attribute.
"""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.stopped = Event()
def stop(self) -> None:
"""
Tell the thread it should stop.
This method merely signals to the thread that it should stop. Calling
code must subsequently call the :meth:`.join` method to wait for the
thread to actually stop. It is an error to call :meth:`.stop` on a
thread which isn't alive (running).
The thread's running code must periodically check if :attr:`.stopped`
has been set, otherwise this method will have no effect. It can do
this in a loop, for example, with a short wait time::
while not self.stopped.wait(0.2):
# periodic work here
...
"""
assert self.is_alive(), "Thread not alive"
self.stopped.set()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment