python 协程

Posted 筱筱的春天

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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......

 


 

以上是关于python 协程的主要内容,如果未能解决你的问题,请参考以下文章

Python 协程

Python3 协程相关

python之协程

Python协程之asyncio

python之协程

python协程