[英]How to await gathered group of tasks?
I have that code我有那个代码
import asyncio
async def f():
await asyncio.sleep(0.1)
print('done')
async def main():
asyncio.create_task(f())
asyncio.create_task(f())
pending = asyncio.all_tasks()
group = asyncio.gather(*pending, return_exceptions=True)
await group
asyncio.run(main())
I don't know why it is working forever.我不知道为什么它一直在工作。 I would like to end program when all tasks from group done their job.
当小组的所有任务完成他们的工作时,我想结束程序。
Python 3.9 Python 3.9
Edit: Ok... I have it.编辑:好的......我有它。
all_tasks
gives me not only tasks that are created by me. all_tasks
给了我自己创建的任务。 Is there any equivalent for all_tasks
but without "main task"? all_tasks
是否有任何等价物但没有“主要任务”?
main
is also coroutine, awaiting main
inside main
will never end. main
也是协程,在main
中等待main
永远不会结束。
{
<Task pending name='Task-2' coro=<f() running at /tmp/t.py:3>>,
<Task pending name='Task-1' coro=<main() running at /tmp/t.py:11> cb=[_run_until_complete_cb() at /home/falsetru/.pyenv/versions/3.9.4/lib/python3.9/asyncio/base_events.py:184]>,
<Task pending name='Task-3' coro=<f() running at /tmp/t.py:3>>
}
Instead, explicitly specifying tasks that call f()
will not block相反,显式指定调用
f()
的任务不会阻塞
async def main():
pending = []
pending.append(f()) # OR pending.append(asyncio.create_task(f()))
pending.append(f())
group = asyncio.gather(*pending, return_exceptions=True)
await group
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.