Python中的协程,gevent模块

# 协程
import time
import gevent
from gevent import monkey

# 猴子补丁
monkey.patch_all()


def a():
    for i in range(5):
        print('A', str(i))
        # 猴子补丁 中 如果需要睡眠效果,必须是time.sleep,因为猴子补丁只是替换了time里面的sleep,如果直接使用
        # from time import sleep
        # sleep()
        # 则无法实现自动切换协程
        time.sleep(0.5)


def b():
    for i in range(5):
        print('B', str(i))
        time.sleep(0.5)


def c():
    for i in range(5):
        print('C', str(i))
        time.sleep(0.5)


if __name__ == '__main__':
    ga = gevent.spawn(a)
    gb = gevent.spawn(b)
    gc = gevent.spawn(c)

    ga.join()
    gb.join()
    gc.join()
posted @ 2021-02-24 02:53  kevin.l  阅读(39)  评论(0编辑  收藏  举报