协程
1 什么是协程
协程(Coroutine)不是计算机硬件提供的,而是编程人员创造的。
协程可以称为微线程,运行方式是在一个线程中在代码之间不断切换游走。
2 实现协程
早期模块:greenlet
yield关键字
内置模块:asyncio(Python 3.4)
关键字:async,await(Python 3.5)
2.1 greenlet模块
from greenlet import greenlet
def func1():
print('func1 1') # 2 打印func1 1
gr2.switch() # 3 切换至婚车
print('func1 2') # 6 打印func1 2
gr2.switch() # 7 切换func2
def func2():
print('func2 1') # 4 打印func2 1
gr1.switch() # 5 切换func1
print('func2 2') # 8 打印func2 2
gr1 = greenlet(func1)
gr2 = greenlet(func2)
gr1.switch() # 1 执行func1
2.2 yield关键字
def func1():
yield 1
yield from func2() # 跳到生成器func2()中
yield 2
def func2():
yield 3
yield 4
f1 = func1()
for item in f1:
print(item)
'''
1
3
4
2
'''
2.3 asyncio模块
遇到IO等阻塞操作时,自动切换。
import asyncio
@asyncio.coroutine
def func1():
print(1)
yield from asyncio.sleep(1) # 遇到阻塞操作时,自动切换到task_list中的其它任务。
print(2)
@asyncio.coroutine
def func2():
print(3)
yield from asyncio.sleep(1) # 遇到耗时操作时,自动切换到task_list中的其它任务。
print(4)
task_list = [
asyncio.ensure_future(func1()),
asyncio.ensure_future(func2()),
]
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(asyncio.wait(task_list))
'''
1
3
2
4
'''
2.4 关键字 async和await
import asyncio
async def func1():
print(1)
await asyncio.sleep(1)
print(2)
async def func2():
print(3)
await asyncio.sleep(1)
print(4)
task_list = [
asyncio.ensure_future(func1()),
asyncio.ensure_future(func2()),
]
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(asyncio.wait(task_list))
3 协程的意义
在一个线程中遇到IO等阻塞操作时,这个线程不会等待,而是去做其它的事情。