import functools import time class Loop: def __init__(self): self.queue = [] self.stoped = False def call_later(self, delay, callback): self.queue.append({"when": time.time() + delay, "callback": callback}) self.queue.sort(key = lambda item: item["when"]) def stop(self): self.stoped = True def loop(self): while (not self.stoped) and len(self.queue) > 0: now = time.time() ready = [] while len(self.queue) > 0 and self.queue[0]["when"] < now: ready.append(self.queue[0]) del self.queue[0] for item in ready: try: item["callback"]() except: pass if len(self.queue) > 0: wakeTime = self.queue[0]["when"] time.sleep(wakeTime - now) class Fututre: def __init__(self): self.callbacks = [] self.result = None def add_done_callback(self, callback): self.callbacks.append(callback) def set_result(self, result): try: self.result = result for callback in self.callbacks: try: callback(self) except: pass except StopIteration: pass def coroutine(func): @functools.wraps(func) def wrap(): result = func() future = Fututre() yielded = next(result) yielded.add_done_callback(lambda fut:future.set_result(fut.result)) def callback(future): result.send(future.result) future.add_done_callback(callback) return wrap loop = Loop() @coroutine def f(): r = yield g() print(r) def g(): future = Fututre() def callback(): future.set_result("OK") loop.stop() loop.call_later(3, callback) return future @coroutine def f1(): r = yield g1() print(r) def g1(): future = Fututre() def callback(): future.set_result("G1") loop.call_later(1, callback) return future f() f1() loop.loop()
python tornado coroutine 原理
最新推荐文章于 2024-03-21 17:08:45 发布