Piotr Wasilewicz
Piotr Wasilewicz

Reputation: 1821

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

Edit: Ok... I have it. all_tasks gives me not only tasks that are created by me. Is there any equivalent for all_tasks but without "main task"?

Upvotes: 2

Views: 1057

Answers (1)

falsetru
falsetru

Reputation: 369044

main is also coroutine, awaiting main inside main will never end.

{
    <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

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

Upvotes: 2

Related Questions