1.使用greenlet库实现
greenlet库是一个实现协程的库,是一个早期的实现协程的方式,它并不是python自带的库,所有在使用前需要下载这个库(pip install greenlet,当然使用国内源会下载的更快一点)
from greenlet import greenlet
def fun1():
print(1) # 1.打印1
gr2.switch() # 2.跳转到fun2()函数
print(2) # 5.打印2
gr2.switch() # 6.跳转到fun2()函数
def fun2():
print(3) # 3.打印3
gr1.switch() # 4.跳转到fun1()函数
print(4) # 7.打印4
gr1 = greenlet(fun1)
gr2 = greenlet(fun2)
gr1.switch() # 先执行fun1()函数
2.使用yield生成器
def func1():
yield 1
yield from func2()
yield 2
def func2():
yield 3
yield 4
f1 = func1()
for item in f1:
print(item)
3.使用asyncio实现协程
在python3.4的标准库中引入了asyncio来实现对异步io的支持,在python3.5中添加了async和await这两个关键字,分别用来替换asyncio.coroutine和yield from。
import asyncio
async def func1():
print(1)
await asyncio.sleep(2)
print(2)
async def func2():
print(3)
await asyncio.sleep(2)
print(4)
tasks = [
asyncio.ensure_future(func1()),
asyncio.ensure_future(func2())
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))