“Why does asyncio.gather() not run my coroutines concurrently when one of them contains a blocking function, and what is the correct way to fix it?”

1 day ago 7
ARTICLE AD BOX

I have following code

import asyncio import time async def task1(): print("task1 start") time.sleep(2) # intentionally blocking print("task1 end") async def task2(): print("task2 start") await asyncio.sleep(1) print("task2 end") async def main(): await asyncio.gather(task1(), task2()) asyncio.run(main())

I expected both tasks to run concurrently, but task2 only starts after task1 finishes. Why doesn’t asyncio.gather() run them concurrently here? What is the correct way to make task1 non-blocking? Should I replace time.sleep() with something else, or run it in a different thread?

Read Entire Article