Skip to content

Instantly share code, notes, and snippets.

@jesseops
Created September 15, 2016 17:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesseops/cecca63265eba330c6c5dd0d7749e650 to your computer and use it in GitHub Desktop.
Save jesseops/cecca63265eba330c6c5dd0d7749e650 to your computer and use it in GitHub Desktop.
Playing with Blinker (and threads )
import blinker
import threading
from time import sleep
# Create a blinker
shutdown = blinker.signal('shutdown', doc="you should shutdown when this signal is triggered")
class Worker(threading.Thread):
def __init__(self, name):
super(Worker, self).__init__()
self.name = name
self._shutdown = False
self.setup_shutdown_handler()
def run(self):
while not self._shutdown:
print "{} is running".format(self.name)
sleep(1)
def setup_shutdown_handler(self):
def _call_shutdown(sender, **kwargs):
self.handle_shutdown(sender, **kwargs)
self._call_shutdown = _call_shutdown
shutdown.connect(_call_shutdown)
def handle_shutdown(self, sender, **kwargs):
if kwargs['name'] == self.name:
self._shutdown = True
else:
print "{} is ignoring shutdown request for {}".format(self.name, kwargs['name'])
if __name__ == "__main__":
workers = []
for i in xrange(5):
workers.append(Worker('worker{}'.format(i)))
for w in workers:
w.start()
sleep(5)
for worker in workers:
if worker.is_alive():
shutdown.send('shutdown please', name=worker.name)
else:
worker.join()
sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment