I have a slow function in python that I want to run asynchronously. This slow function is basically a very long loop, like the following:
def slow(slowness):
print(f"Slow loop {slowness}")
for i in range(int(slowness * 1e8)):
i
print(f"Wait for loop {slowness} finished")
if __name__ == '__main__':
slow(1)
slow(0.5)
slow(0.1)
I'm trying to run the asynchronous version, using the following code:
import asyncio
async def slow(slowness):
print(f"Slow loop {slowness}")
for i in range(int(slowness * 1e8)):
i
print(f"Wait for loop {slowness} finished")
async def main() -> None:
await asyncio.gather(
slow(1),
slow(0.5),
slow(0.1)
)
if __name__ == '__main__':
asyncio.run(main())
I would expect the function with slowness=0.1 to finish the execution first, but I am seeing a regular execution that seems synchronous. What am I doing wrong?
I'm seeing the following output:
Waiting for 1 seconds...
Wait for 1 seconds finished
Waiting for 0.5 seconds...
Wait for 0.5 seconds finished
Waiting for 0.1 seconds...
Wait for 0.1 seconds finished
and I'd expect something like:
Waiting for 1 seconds...
Waiting for 0.5 seconds...
Waiting for 0.1 seconds...
Wait for 0.1 seconds finished
Wait for 0.5 seconds finished
Wait for 1 seconds finished