python tornado coroutine 原理

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值