5

I'm new to Python asyncio and I'm doing some experiments. I have the following code:

async def say_after(n, s):
    await asyncio.sleep(n)
    print(s)

async def main():
    task1 = asyncio.create_task(say_after(2, 'a'))
    task2 = asyncio.create_task(say_after(1, 'b'))
    await task1
    print('x', flush=True)
    await task2
    print('y', flush=True)

asyncio.run(main())

And the output:

b
a
x
y

I don't understand the order here. Can someone help explain? Especially why x comes after b and a?

  • 1
    If you try the code it actually only prints `x` and `y`. If you await the tasks, the output is the following: `x y b a` – Łukasz Kwieciński Jan 22 '22 at 15:41
  • @ŁukaszKwieciński Hi sorry I copied a wrong version of the code... I have updated the code and it should produce the same output as in the question. – Weiss Zucker Jan 22 '22 at 17:40
  • 3
    Already burned my closure vote prior to the edit (thanks, much clearer now!), but I think [What does asyncio.create_task() do?](https://stackoverflow.com/questions/62528272/what-does-asyncio-create-task-do) is the proper answer. You're spawning new tasks; simply omit this call if you want to keep everything sequential in a single task. – ggorlen Jan 22 '22 at 18:10
  • @ggorlen thanks! This one really helped me to understand what is a task. – Weiss Zucker Jan 22 '22 at 18:42

1 Answers1

0

Especially why x comes after b and a?

b is printed in task2 about 1 second after the start of main, and a is printed in task1 about 2 seconds after the start of main. The await task1 waits for task1, and so waits about 2 seconds. So by the time await task1 completes, both b and a would have been printed.

(The "about"s in the above are deliberate... there would be variations, but in most situations, they would be small)

Michal Charemza
  • 24,475
  • 11
  • 89
  • 143