目录
一.协程
协程不是计算机提供,是程序员人为创造,又称为微线程
协程是一种用户态内的上下文切换技术,简而言之,其实就是通过一个线程实现代码块相互切换执行
实现协程的方法:
- greenlet,早期模块
- yield关键字
- asynico装饰器(Python3.4)
- async,await关键字(Python3.5版本之后使用)
1.1 greenlet实现协程
安装greenlet
pip3 install greenlet
from greenlet import greenlet
def fun1():
print(1) #1
gr2.switch()#切换到fun2函数
print(2)#2
gr2.switch()#切换到fun2函数
def fun2():
print(3)#3
gr1.switch()#切换到fun1函数
print(4)#4
gr1 = greenlet(fun1)
gr2 = greenlet(fun2)
gr1.switch()#执行fun1函数
运行结果:
1
3
2
4
1.2 yield关键字
def fun1():
yield 1
yield from fun2()
yield 2
def fun2():
yield 3
yield 4
f1 = fun1()
for item in f1:
print(item)
1.3 asynico
import asyncio
@asyncio.coroutine
def fun1():
print(1)
yield from asyncio.sleep(2) # 遇到IO操作耗时,自动切换到task中的其他任务
print(2)
@asyncio.coroutine
def fun2():
print(3)
yield from asyncio.sleep(2)
print(4)
tasks = [
asyncio.ensure_future(fun1()),
asyncio.ensure_future(fun2())
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
1.4async和await关键字
import asyncio
async def fun1():
print(1)
await asyncio.sleep(2) # 遇到IO操作耗时,自动切换到task中的其他任务
print(2)
async def fun2():
print(3)
await asyncio.sleep(2)
print(4)
tasks = [
asyncio.ensure_future(fun1()),
asyncio.ensure_future(fun2())
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))