[英]How to run two task concurrently with Python async/await?
代碼:
import asyncio
async def f1():
print('f1:1')
await asyncio.sleep(2)
print('f1:2')
async def f2():
print('f2:1')
await asyncio.sleep(2)
print('f2:2')
async def f():
await f1()
await f2()
asyncio.run(f())
結果:
f1:1
f1:2
f2:1
f2:2
我期望的是同時運行f1
和f2
,結果是:
f1:1
f2:1
f1:2
f2:2
那么有人可以給我一些建議嗎?
使用收集() :
import asyncio
async def f1():
print('f1:1')
await asyncio.sleep(2)
print('f1:2')
async def f2():
print('f2:1')
await asyncio.sleep(2)
print('f2:2')
async def f():
await asyncio.gather(f1(), f2())
asyncio.run(f())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.