Home > Mobile >  asyncio wait until complete task children
asyncio wait until complete task children

Time:05-30

In asyncio I want to write code to create a task for example called "something", which is "something"; Creates other new tasks. When the tasks created by "something" are completed, I want the 'complete all tasks' sentence to be printed.

Output I want:
start tasks
# before and after ...
complete all tasks

code:



async def st(n):
    print('before ', n)
    await asyncio.sleep(3)
    print('after ', n)


async def tt(n):
    for i in range(n):
        asyncio.create_task(st(n))


async def main():
    print('start tasks ...')
    loop = asyncio.create_task(tt(3),name='something')
    await loop
    print('complete all tasks')


asyncio.run(main())

CodePudding user response:

If you want to wait for something to happen in asyncio, that's generally a clue you need to use the await command. Calling asyncio.create_task doesn't actually cause a task to run; tasks only run when another task yields control by calling await.

Assuming that you want the st() tasks to run concurrently, something like this would work:

import asyncio


async def st(n):
    print("before ", n)
    await asyncio.sleep(3)
    print("after ", n)


async def tt(n):
    tasks = []
    for i in range(n):
        tasks.append(st(i))

    await asyncio.gather(*tasks)


async def main():
    print("start tasks ...")
    await tt(3)
    print("complete all tasks")


asyncio.run(main())

In tt(), we append each new coroutine to the tasks list, and then use asyncio.gather to execute the tasks concurrently.

You'll note that we never need to call asyncio.create_task here: asyncio.gather takes care executing things for us, and in main we're only running a single coroutine so we can just await on it directly.

Running the above code results in output like this:

start tasks ...
before  0
before  1
before  2
after  0
after  1
after  2
complete all tasks
  • Related