'await vs asyncio.sleep: Does await keyword return control to the loop? Or maybe Pythons's asyncio StreamReader.read() is blocking?
I encountered a strange situation. StreamReader in asyncio seems to be blocking.
received = asyncio.Queue()
async def read_loop():
while True:
received_data = await reader.read(4096)
await received.put(received_data)
Then when I do
task = asyncio.create_task(read_loop())
# some time later....
task.cancel()
The task won't get cancelled. However, when I add one single line to this function:
async def read_loop():
while True:
asyncio.sleep(0) # THIS LINE
received_data = await reader.read(4096)
await received.put(received_data)
Everything is working and the task gets cancelled.
It's like the await before reader.read doesn't return control to the event loop. I thought both await and asyncio.sleep return control to the event loop.
I want to understand why adding the sleeping function helped. I'd be grateful for help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|