python 协程

1.协程定义

不开辟新的线程的基础上,实现多个任务,是个特殊的生成器。一秒钟能切换上百次。

2.原始版协程

import time

#1.work1 生成器
def work1():
    while True:
        print("executing work1......")
        yield
        time.sleep(0.5)

#2.work2 生成器
def work2():
    while True:
        print("executing work2......")
        yield
        time.sleep(0.5)

#3.获取生成器
#4.协程运行
if __name__ == '__main__':
    w1=work1()
    w2=work2()
    while True:
        next(w1)
        next(w2)

执行结果
executing work1......
executing work2......
executing work1......
executing work2......
executing work1......
executing work2......

 


 

posted @ 2023-03-23 14:46  筱筱的春天  阅读(30)  评论(0编辑  收藏  举报