-
-
Save rightfold/085553c515b02a9458f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from threading import Lock, Thread | |
class Worker: | |
def __init__(self, once): | |
self.__thread = None | |
self.__running_lock = Lock() | |
self.__running = False | |
self.__once = once | |
def __loop(self): | |
while True: | |
with self.__running_lock: | |
if not self.__running: | |
break | |
self.__once() | |
def start(self): | |
with self.__running_lock: | |
if self.__running: | |
return | |
self.__running = True | |
self.__thread = Thread(target=self.__loop) | |
self.__thread.start() | |
def stop(self): | |
with self.__running_lock: | |
if not self.__running: | |
return | |
self.__running = False | |
self.__thread.join() | |
self.__thread = None | |
def __enter__(self): | |
pass | |
def __exit__(self, exc_type, exc_value, traceback): | |
self.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment