简体   繁体   English

如何等待收集的任务组?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM