Async Coroutines and asyncio.gather
Write non-blocking concurrent code using coroutines.
Learning objectives
- Understand async def coroutines and the await keyword
- Run multiple tasks concurrently with asyncio.gather()
Lesson material
Coroutines with asyncio
Async IO enables single-threaded concurrent cooperative multitasking.
Example code
import asyncio
async def fetch_data(id: int):
await asyncio.sleep(0.01) # Simulate non-blocking I/O
return f"Data {id}"
async def main():
results = await asyncio.gather(fetch_data(1), fetch_data(2))
print(results)
asyncio.run(main())
Practice exercise: Async Worker
Write an async function `async_double(x)` that awaits `asyncio.sleep(0.01)` and returns `x * 2`. Call it inside `main()` with `await asyncio.gather(async_double(5), async_double(10))` and print the result list.
Test yourself with the Module 18: Concurrency & Async IO quiz →