在Python中,yield(生成器)可以很容易的实现上述的功能,从一个函数切换到另外一个函数。
由于比较繁琐,这里不再赘述,可以参考:https://blog.csdn.net/weixin_41599977/article/details/93656042
三、Greenlet模块
Greenlet是一个用C实现的协程模块,相比于python自带的yield,它可以使你在任意函数之间随意切换,而不需把这个函数先声明为generator。
安装:
pip3 install greenlet
使用:
from greenlet importgreenletimporttimedeftask_1():whileTrue:print("--This is task 1!--")
g2.switch()#切换到g2中运行
time.sleep(0.5)deftask_2():whileTrue:print("--This is task 2!--")
g1.switch()#切换到g1中运行
time.sleep(0.5)if __name__ == "__main__":
g1= greenlet(task_1) #定义greenlet对象
g2 =greenlet(task_2)
g1.switch()#切换到g1中运行
运行输出:
--This is task 1!--
--This is task 2!--
--This is task 1!--
--This is task 2!--
--This is task 1!--
--This is task 2!--
--This is task 1!--
--This is task 2!--
四、Gevent模块
Greenlet已经实现了协程,但是这个需要人工切换,很麻烦。
Python中还有一个能够自动切换任务的模块gevent,其原理是当一个greenlet遇到IO操作(比如网络、文件操作等)时,就自动切换到其他的greenlet,等到IO操作完成,在适当的时候切换回来继续执行。
由于IO操作比较耗时,经常使程序处于等待状态,有了gevent为我们自动切换协程 ,就保证总有greenlet在运行,而不是等待IO。
安装:
pip3 install gevent
用法:
g1=gevent.spawn(func,1,2,3,x=4,y=5)#创建一个协程对象g1,spawn括号内第一个参数是函数名,如eat,后面可以有多个参数,可以是位置实参或关键字实参,都是传给函数eat的,spawn是异步提交任务
g2=gevent.spawn(func2)
g1.join()#等待g1结束
g2.join()#等待g2结束 有人测试的时候会发现,不写第二个join也能执行g2,是的,协程帮你切换执行了,但是你会发现,如果g2里面的任务执行的时间长,但是不写join的话,就不会执行完等到g2剩下的任务了
#或者上述两步合作一步:
gevent.joinall([g1,g2])
g1.value#拿到func1的返回值
遇到IO阻塞时会自动切换任务:
importgeventdefeat(name):print('%s eat 1' %name)
gevent.sleep(2)print('%s eat 2' %name)defplay(name):print('%s play 1' %name)
gevent.sleep(1)print('%s play 2' %name)
g1= gevent.spawn(eat, 'egon')
g2= gevent.spawn(play, name='egon')
g1.join()
g2.join()#或者gevent.joinall([g1,g2])
上例gevent.sleep(2)模拟的是gevent可以识别的IO阻塞。
而time.sleep(2)或其他的阻塞,gevent是不能直接识别的。需要用下面一行代码打补丁,就可以识别了:
from gevent importmonkey;
monkey.patch_all()#必须放到被打补丁者的前面,如time,socket模块之前
或者我们干脆认为:要用gevent,需要将from gevent import monkey;monkey.patch_all()放到文件的开头:
from gevent importmonkey
monkey.patch_all()#必须写在最上面,这句话后面的所有阻塞全部能够识别了
import gevent #直接导入即可
importtimedefeat():#print()
print('eat food 1')
time.sleep(2) #加上monkey就能够识别到time模块的sleep了
print('eat food 2')defplay():print('play 1')
time.sleep(1) #来回切换,直到一个I/O的时间结束,这里都是我们个gevent做得,不再是控制不了的操作系统了。
print('play 2')
g1=gevent.spawn(eat)
g2=gevent.spawn(play)
gevent.joinall([g1, g2])print('主')
协程是通过自己的程序(代码)来进行切换的,只有遇到协程模块能够识别的IO操作的时候,程序才会进行任务切换,实现并发效果,如果所有程序都没有IO操作,那么就基本属于串行执行了。
五、Python3.x协程
Python3.x系列的协程有很多不同的地方,这里介绍下主要的:
1、asyncio
asyncio是Python3.4引进的标准库,直接内置了对IO的支持,asyncio的操作,需要在coroutine中通过yield from完成。
importasyncio
@asyncio.coroutinedefget_body(i):print(f'start{i}')yield from asyncio.sleep(1)print(f'end{i}')
loop=asyncio.get_event_loop()
tasks= [get_body(i) for i in range(5)]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
输出结果:
start4
start0
start1
start3
start2
end4
end0
end1
end3
end2
它的效果是和Gevent一样的,遇到IO操作的时候,自动切换上下文。
不同的是,它对tasks的操作:task先把这个5个参数不同的函数全部加载进来,然后执行任务,任务执行是无序的。
@asyncio.coroutine把一个generator标记为coroutine类型,然后把这个coroutine扔到eventloop中执行
yield from 语法让我们方便的调用另一个generator。由于asyncio.sleep()也是一个coroutine,线程不会等待,直接中断执行下一个消息循环。当asyncio.sleep()返回时,线程可以从yield from拿到返回值(此处是None),然后接着执行下一行语句。
2、async/await
在Python3.5的时候,asyncio添加了两个关键字aysnc和await,让coroutine语法更简洁。