I have read When will/won't Python suspend execution of a coroutine?, the accepted anwser mentions:
It is worth mentioning that asyncio.sleep is explicitly guaranteed to suspend execution and defer to the event loop, even when the specified delay is 0 (in which case it will immediately resume on the next event loop pass)."
From python doc https://docs.python.org/3/library/asyncio-dev.html#concurrency-and-multithreading:
When a Task executes an await expression, the running Task gets suspended, and the event loop executes the next Task.
But in my following example, it didn't suspend when it meet await asyncio.sleep(0.1)
in do_something
, What is the problem of my understanding?
import asyncio
async def do_something(i):
await asyncio.sleep(0.1)
print('in do_something')
async def main():
for i in range(10):
print(i)
await do_something(i)
t1 = time.time()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
print('cost time:', time.time() - t1)
expected output:
0
1
2
3
4
5
6
7
8
9
in do_something
in do_something
in do_something
in do_something
in do_something
in do_something
in do_something
in do_something
in do_something
in do_something
cost time: 1.0283539295196533
Real output:
in do_something
1
in do_something
2
in do_something
3
in do_something
4
in do_something
5
in do_something
6
in do_something
7
in do_something
8
in do_something
9
in do_something
cost time: 1.0283539295196533