Created
March 18, 2013 21:09
-
-
Save enaeseth/5190833 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
""" | |
Interruptible worker pattern | |
""" | |
import threading | |
class Worker(object): | |
def __init__(self): | |
self._running = False | |
self._wakeup = threading.Condition() | |
def start(self): | |
with self._wakeup: | |
if self._running: | |
raise RuntimeError | |
self._running = True | |
self._thread = threading.Thread(target=self._run) | |
self._thread.start() | |
def stop(self): | |
with self._wakeup: | |
if not self._running: | |
raise RuntimeError | |
self._running = False | |
self._wakeup.notify_all() | |
self._thread.join() | |
def _run(self): | |
while self._running: | |
# Do our task | |
self.do_actual_work() | |
# Sleep for five seconds before trying to do more work | |
with self._wakeup: | |
self._wakeup.wait(5.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment