Issue
I am just starting to learn about asynchronous programming, in particular the async
and await
syntax and usage of the asyncio
module.
My question is regarding the output of the following code:
import asyncio
async def foo():
print('start fetching')
await asyncio.sleep(2)
print('done fetching')
return {'data':1}
async def boo():
for i in range(10):
print(i)
await asyncio.sleep(0.25)
async def main():
task1 = asyncio.create_task(foo())
task2 = asyncio.create_task(boo())
asyncio.run(main())
The output that I get is:
start fetching
0
While I understand what each individual part of the code does, I can't understand why only two lines of the code is being outputted. Here is my understanding:
- We start with
task1
and printstart fetching
. - Then we hit the await for 2 seconds.
- In these two seconds doesn't this give
task2
the opportunity to do its execution for 2 seconds, so 0-8 will be printed? - Then I also don't see why we don't continue executing the function
foo()
? – i.e.print('done fetching')
?
Solution
asyncio.run()
has two extra event loop iterations internally, they are used for shutdown:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.run_until_complete(loop.shutdown_default_executor())
Running these calls gives previously scheduled tasks a chance to iterate over up to 2 times.
Note: this is an implementation detail that may be changed at any time (the number of iterations for startup/shutdown of the event loop can be modified in future Python versions).
Please don't rely on this behavior in your code, but explicitly await scheduled tasks to correctly process them.
Answered By - Andrew Svetlov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.