Issue
Why is there a different how tasks are run between tasks 1-3 and 4-6 in the code below?
Code:
import asyncio
async def do_something(i, sleep): # No I/O here
print("Doing... ", end="")
print(await no_io_1(i, sleep))
async def no_io_1(i, sleep): # No I/O here
return await no_io_2(i, sleep)
async def no_io_2(i, sleep): # No I/O here
return await io(i, sleep)
async def io(i, sleep):
await asyncio.sleep(sleep) # Finally some I/O
# t = asyncio.create_task(asyncio.sleep(sleep))
# await t
return i
async def main():
await asyncio.create_task(do_something(1, sleep=4))
await asyncio.create_task(do_something(2, sleep=3))
await asyncio.create_task(do_something(3, sleep=2))
t4 = asyncio.create_task(do_something(4, sleep=4))
t5 = asyncio.create_task(do_something(5, sleep=3))
t6 = asyncio.create_task(do_something(6, sleep=2))
await t4
await t5
await t6
asyncio.run(main())
print("\r\nBye!")
Output:
Doing... 1
Doing... 2
Doing... 3
Doing... Doing... Doing... 6
5
4
Solution
In the first snippet you immediately await each task you've created. As a result, the tasks are prevented from running in parallel.
In the second snippet you create three tasks and only then start awaiting. This allows all three to run in parallel, despite you await
specifying you're interested in the result of the first one. (Being able to run other tasks while waiting for the results of a specific one a core design goal of libraries like asyncio.)
In other words, await t1
doesn't mean "run t1
", it means "suspend me and spin the event loop until t1
is done". The difference has nothing to do with tasks being stored in variables, but with creating tasks at once. For example, you could modify the second example like this:
t4 = asyncio.create_task(do_something(4, sleep=4))
await t4
t5 = asyncio.create_task(do_something(5, sleep=3))
await t5
t6 = asyncio.create_task(do_something(6, sleep=2))
await t6
...and you would get behavior like that of the first example.
Answered By - user4815162342
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.