关于python:gevent

70次阅读

共计 798 个字符,预计需要花费 2 分钟才能阅读完成。

# gevent/greenlet.py
class Greenlet(greenlet):
    def __init__(self, run=None, *args, **kwargs):
        _greenlet__init__(self, None, get_hub()) # 指定 hup 为 parent
        self._run = run # Greenlet.switch 切换会调用 run 函数
    @classmethod
    def spawn(cls, *args, **kwargs):
        g = cls(*args, **kwargs)
        g.start()
        return g
    def start(self):
        if self._start_event is None:
            self._start_event = self.parent.loop.run_callback(self.switch) # 注册 swtich 到 loop
    def run(self):
        self._run(*self.args, **self.kwargs)
# gevent/hup.py
class Hub(WaitOperationsGreenlet):
    def run(self): # Hup.switch 切换会调用 run 函数
        while 1:
            try:
                self.loop.run() # 事件循环 run
            finally:
                loop.error_handler = None # break the refcount cycle

import gevent

def test1():
    print('进入 test1')
    gevent.sleep(0)
    print('切换 test1')

def test2():
    print('进入 test2')
    gevent.sleep(0)
    print('切换 test2')

gevent.joinall([gevent.spawn(test1),
    gevent.spawn(test2),
]) 

进入 test1
进入 test2
切换 test1
切换 test2

正文完
 0