我在 Python 3.9 中嘗試了新的 asyncio 功能,并具有以下代碼:
import asyncio
async def inc(start):
i = start
while True:
print(i)
i = 2
return None
async def main():
x = asyncio.gather(
asyncio.to_thread(inc, 0),
asyncio.to_thread(inc, 1)
)
try:
await asyncio.wait_for(x, timeout=5.0)
except asyncio.TimeoutError:
print("timeout!")
asyncio.run(main())
我的期望是該程式將列印從 5 秒開始0并在 5 秒后終止的數字。但是,當我在這里執行程式時,我看不到任何輸出和以下警告:
/usr/lib/python3.9/asyncio/events.py:80: RuntimeWarning: coroutine 'inc' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
/usr/lib/python3.9/concurrent/futures/thread.py:85: RuntimeWarning: coroutine 'inc' was never awaited
del work_item
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
uj5u.com熱心網友回復:
asyncio.to_thread將常規函式轉換為協程。
您只需async def inc將def inc. 你可以這樣做,因為沒有await,它不是真正的協程。
但是,您不能殺死執行緒。超時將導致停止等待,而不是停止計算數字。
更新:詳細地說,asyncio.gather等待協程直到超時。當超時取消時,gather取消所有仍在運行的協程 a 并等待它們的終止。await取消協程意味著在最近的陳述句處傳遞例外。在這種情況下,沒有await,協程將永遠不會收到取消例外。程式此時掛起。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/429533.html
上一篇:物件轉換期間執行緒“主”錯誤中的例外[java.lang.ClassCastException]-如何解決轉換問題?
