-1

When running multiple coroutines concurrently using asyncio gather, the function creates task for each item. Now I want to get parent task which hash gather function in it! Is there a way to get parent task?

1
  • Can you please clarify your constraints? Should the child task autonomously identify and access the parent task? Can the parent task be modified to simplify/solve the problem? Commented Sep 27, 2021 at 17:48

2 Answers 2

1

I do not see any "from a box" method to access "parent" task from "child", on the other hand you can just provide "child" task with reference to "parent" task and get all information regarding the parent task by the reference:

import asyncio


async def test_task(parent_task: asyncio.Task):
    await asyncio.sleep(1)
    print(f"Parent task name: {parent_task.get_name()}")
    await asyncio.sleep(1)


async def amain():
    print("Parent Task Start working")
    await asyncio.gather(test_task(asyncio.current_task()))
    print("Parent task Task Finished working")

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    _parent_task = loop.create_task(amain(), name="Parent Task")
    loop.run_until_complete(_parent_task)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use asyncio.current_task for this:

test.py:

import asyncio
  

async def task(i, m):
    print(f"START: {i} ({m.get_name()})")
    await asyncio.sleep(i * 0.5)
    print(f"END: {i}")


async def main():
    m = asyncio.current_task()
    tasks = []

    for i in range(5):
        tasks.append(asyncio.create_task(task(i, m)))

    await asyncio.gather(*tasks)


if __name__ == "__main__":
    asyncio.run(main())

Test:

$ python test.py
START: 0 (Task-1)
START: 1 (Task-1)
START: 2 (Task-1)
START: 3 (Task-1)
START: 4 (Task-1)
END: 0
END: 1
END: 2
END: 3
END: 4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.