Having read the documents and watched a number of videos, i am testing asyncio
as an alternative to threading
.
The docs are here: https://docs.python.org/3/library/asyncio.html
I have constructed the following code with the expectation that it would produce the following.
before the sleep
hello
world
But in fact is produces this (world
comes before hello
):
before the sleep
world
hello
Here is the code:
import asyncio
import time
def main():
''' main entry point for the program '''
# create the event loop and add to the loop
# or run directly.
asyncio.run(main_async())
return
async def main_async():
''' the main async function '''
await foo()
await bar()
return
async def foo():
print('before the sleep')
await asyncio.sleep(2)
# time.sleep(0)
print('world')
return
async def bar():
print('hello')
await asyncio.sleep(0)
return
if __name__=='__main__':
''' This is executed when run from the command line '''
main()
The main()
function calls the async main_async()
function which in turn calls both the foo
and bar
async functions and both of those run the await asyncio.sleep(x)
command.
So my question is: why is the hello
world
comming in the wrong (unexpected) order given that i was expecting world
to be printed approximately 2 seconds after hello
?