[英]Running functions concurrently in python asyncio
我正在使用 python 3.6 並嘗試使用 asyncio 並發運行任務。 我認為 asyncio.gather 並確保未來將成為使用的工具,但它似乎並沒有像我想象的那樣工作。 有人可以給我指點嗎?
這是我的代碼:
import time
import asyncio
async def f1():
print('Running func 1')
time.sleep(4)
print('Returning from func 1')
return 1
async def f2():
print('Running func 2')
time.sleep(6)
print('Returning from func 2')
return 2
async def f3():
print('Running func 3')
time.sleep(1)
print('Returning from func 3')
return 3
async def foo():
calls = [
asyncio.ensure_future(f())
for f in [f1, f2, f3]
]
res = await asyncio.gather(*calls)
print(res)
loop = asyncio.get_event_loop()
start = time.time()
loop.run_until_complete(foo())
end = time.time()
print(f'Took {end - start} seconds')
print('done')
我希望這 3 個功能彼此獨立運行,但每個功能似乎都被阻止在另一個之后。 這是我得到的輸出
Running func 1
Returning from func 1
Running func 2
Returning from func 2
Running func 3
Returning from func 3
[1, 2, 3]
Took 11.009816884994507 seconds
done
我原以為它需要 6 秒,瓶頸是 f2。
首先,歡迎來到 StackOverflow。
當您在事件循環中運行代碼時,如果您不想阻塞整個過程,則此代碼必須使用異步庫或在執行程序中運行。
通過這種方式,事件循環可以發送要在工作線程中或事件循環本身中執行的任務背景,以防您使用異步庫。 同時,事件循環可以處理新函數或代碼的一部分並重復相同的過程。
一旦任何后台任務完成,事件循環就會捕獲它們並返回其值。
在您的情況下,如果您使用異步睡眠庫,您應該獲得預期的結果。 例如:
async def f1():
print('Running func 1')
await asyncio.sleep(4)
print('Returning from func 1')
return 1
我沒有閱讀本教程,但我希望找到您的解決方案應該很有趣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.