from threading import Thread, Condition from queue import Queue class WriterConsumerEx(Thread): def __init__(self, handler): Thread.__init__(self) self._cond = Condition() self._messages = Queue() self._stopped = False self._handler = handler def run(self): while True: with self._cond: while self._messages.empty(): self._cond.wait() while self._messages.empty() is False: method, params = self._messages.get() self._handler.write(method, params) self._messages.task_done() if self._stopped == True: break def put(self, method,params): with self._cond: self._messages.put((method, params)) self._cond.notify() def quit(self): with self._cond: self._stopped = True self._cond.notify()