直接看官方文档:协程与任务 — Python 3.11.4 文档
在使用sanic框架后,以为await是非阻塞地运行后面的函数,但是在自己写的demo里,如下:
import asyncio
import time
async def foo_main():
await foo_1()
await foo_2()
async def foo_1():
print("foo1 start", time.strftime('%X'))
await asyncio.sleep(5)
print("foo1 end", time.strftime('%X'))
async def foo_2():
print("foo2 start", time.strftime('%X'))
await asyncio.sleep(5)
print("foo2 end", time.strftime('%X'))
if __name__ == '__main__':
asyncio.run(foo_main())
发现和同步的一样,是阻塞的。 改成下面这种才可以:
async def foo_main():
t1 = asyncio.create_task(foo_1())
t2 = asyncio.create_task(foo_2())
await t1
await t2
区别在于原先await后面接的是coroutine对象,改后的t1是Task对象。
注意,这么写也不行:
async def foo_main():
await asyncio.create_task(foo_1())
await asyncio.create_task(foo_2())
因为创建多个任务才能并行跑。
主要结论
并行和异步不等价