Python 简易的异步协程使用方法
代码
import asyncio
async def ex(id, n):
print(id+" start")
await asyncio.sleep(n/2)
print(id+" 1/2")
await asyncio.sleep(n/2)
print(id+" 2/2")
return n + 1
async def go():
c1 = ex("one", 4)
c2 = ex("two", 6)
await asyncio.gather(c1, c2)
g = go()
asyncio.run(g)
结果
one start
two start
one 1/2
two 1/2
one 2/2
two 2/2