+
+# 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()