Python中实现协程的方法

协程:简单的来说就是不带有返回值的调用

最基本的实现方法:

  • 利用yeild来实现

import time

def work1(): # 循环打印数字1  

    while True:  

        print("-----1-----") # yield可以暂时挂起该函数,跳转到调用该函数的下方  

        yield # 延迟一秒以便观察  

        time.sleep(1)

def work2():     

    while True:  

        print("-----2-----")  

        yield  

        time.sleep(1)

th1 = work1()

th2 = work2()

while True: # 唤醒被挂起的函数  

    next(th1)  

    next(th2)

  • greenlet也可以实现了协程,但是这个还得人工切换,有点很麻烦,就不介绍了
  • python还有一个能够自动切换任务的模块 gevent 也能实现协程

import gevent

import time

def work1(): # 循环打印  

    while True:  

    print("----1----") # 破解sleep 使sleep不再阻塞  

    gevent.sleep(1)

def work2():  

    while True:  

    print("----2----")  

    gevent.sleep(1)

# 创建并开始执行携程

th1 = gevent.spawn(work1)

th2 = gevent.spawn(work2)

# 阻塞等待携程结束

gevent.joinall([th1,th2])

猜你喜欢

转载自blog.csdn.net/sun_daming/article/details/80035767