Skip to content

Instantly share code, notes, and snippets.

@wickman
Created August 27, 2014 22:49
Show Gist options
  • Select an option

  • Save wickman/dc11896d782f9a2160b8 to your computer and use it in GitHub Desktop.

Select an option

Save wickman/dc11896d782f9a2160b8 to your computer and use it in GitHub Desktop.

Revisions

  1. wickman created this gist Aug 27, 2014.
    36 changes: 36 additions & 0 deletions thread_registry.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    import threading

    from twitter.common import log
    from twitter.common.exceptions import ExceptionalThread


    class ThreadRegistry(ExceptionalThread):
    DEFAULT_WAIT_INTERVAL_SECS = 1.0

    def __init__(self, wait_interval=DEFAULT_WAIT_INTERVAL_SECS):
    self.__threads = []
    super(ThreadRegistry, self).__init__()
    self.daemon = True
    self._stopped = threading.Event()
    self.dead = threading.Event()
    self.lock = threading.Lock()
    self.wait_interval = wait_interval

    def register(self, thread_object):
    with self.lock:
    self.__threads.append(thread_object)

    def unregister(self, thread_object):
    with self.lock:
    self.__threads.remove(thread_object)

    def stop(self):
    self._stopped.set()

    def run(self):
    while not self.dead.is_set() and not self._stopped.wait(timeout=self.wait_interval):
    with self.lock:
    for thread in self.__threads:
    if not thread.is_alive():
    log.error('Thread %s died unexpectedly!' % thread)
    self.dead.set()