我正在閱讀這本書并面對代碼片段,這對我來說沒有意義。有人可以為我澄清一下嗎?
import asyncio
async def main():
print(f'{time.ctime()} Hello!')
await asyncio.sleep(1.0)
print(f'{time.ctime()} Goodbye!')
loop = asyncio.get_event_loop()
task = loop.create_task(main())
loop.run_until_complete(task) # This line is responsible to block the thread (Which is MainThread in my case), until every coroutine won't be finished.
pending = asyncio.all_tasks(loop=loop) # asyncio.all_tasks() Return a set of not yet finished Task objects run by the loop. Based on definition, pending will always be an empty set.
for task in pending:
task.cancel()
group = asyncio.gather(*pending, return_exceptions=True)
loop.run_until_complete(group)
loop.close()
我認為asyncio.all_tasks()應該在loop.run_until_complete()函式之前使用。此外,我還發現了許多其他有用的地方,但這個例子對我來說絕對沒有意義。我真的很感興趣,為什么作者這樣做?重點是什么?
uj5u.com熱心網友回復:
你的想法是正確的。這里沒有意義,.all_tasks()因為它總是回傳一個空集。您只有一項任務,然后將其傳遞給.run_until_complete(),因此它會一直阻塞直到完成。
但是當你有另一個比你的協程花費更長的任務時,情況就會改變main:
import asyncio
import time
async def longer_task():
print("inside longer coroutine")
await asyncio.sleep(2)
async def main():
print(f"{time.ctime()} Hello!")
await asyncio.sleep(1.0)
print(f"{time.ctime()} Goodbye!")
loop = asyncio.new_event_loop()
task1 = loop.create_task(main())
task2 = loop.create_task(longer_task())
loop.run_until_complete(task1)
pending = asyncio.all_tasks(loop=loop)
print(pending)
for task in pending:
task.cancel()
group = asyncio.gather(*pending, return_exceptions=True)
loop.run_until_complete(group)
loop.close()
事件回圈只關心完成task1,因此task2將處于掛起模式。
我認為 asyncio.all_tasks() 應該在 loop.run_until_complete() 函式之前使用。
只要你,即使回圈尚未開始create_task(),它也會包含在回傳的集合中。all_tasks()
附帶說明:(3.10 版)由于您沒有正在運行的事件回圈,.get_event_loop()因此會警告您。改為使用.new_event_loop()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/513484.html
上一篇:如何在不批量反應的情況下更新狀態
