协程实战
只介绍常见用法,底层用法请回顾 yield from,原理请参考论文
cpu密集
对于cpu密集操作,当然只能靠多进程方式
io密集
对于io密集型操作,传统上用多线程方式。
现在,更加高效的的方式来了,协程 !
协程的本质是函数回调,
不需要os调度,效率极高,且不需要锁。
缺点是回调得自己写,代码老复杂了
python3.7 协程代码
官网两个例子
使用 asyncio.create_task() 方法创建任务
import asyncio
async def test():
asyncio.sleep(1)
async def main():
task1 = asyncio.create_task(test())
task2 = asyncio.create_task(test())
await task1
await task2
asyncio.run(main())
使用 asyncio.gather() 方法搜集多个任务
import asyncio
async def who(name):
asyncio.sleep(1)
print(name)
async def main():
# Schedule three calls *concurrently*:
await asyncio.gather(
who('Bob'),
who(