X-Git-Url: https://git.ralfj.de/saartuer.git/blobdiff_plain/83d646a505bed8c75eef15855da7046e5854106d..5bceb6534d5f640dcdd4d5015cecfbad4e82a7b7:/libtuer.py?ds=inline diff --git a/libtuer.py b/libtuer.py index a655fcd..0df4051 100644 --- a/libtuer.py +++ b/libtuer.py @@ -19,3 +19,33 @@ logger = Logger() def log (what): logger.log(what) + +# Threaded callback class +class ThreadFunction(): + _CALL = 0 + _TERM = 1 + + def __init__(self, f): + self._f = f + self._q = queue.Queue() + self._t = threading.Thread(target=self._thread_func) + self._t.start() + + def _thread_func(self): + while True: + (cmd, data) = self._q.get() + # run command + if cmd == _CALL: + self._f(*data) + elif cmd == _TERM: + assert data is None + break + else: + raise NotImplementedError("Command %d does not exist" % cmd) + + def __call__(self, *arg): + self._q.put((self._CALL, arg)) + + def stop(self): + self._q.put((_TERM, None)) + self._t.join()