gevent

# 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

你可能感兴趣的:(python)