Async IOAdvanced
1Question 1 of 1
pythonHow does asyncio enable asynchronous concurrent programming in Python?
Explanation & Concept
The `asyncio` module provides an event loop that runs cooperative multitasking using `async` coroutines and `await`.
Coroutines pause execution at `await` expressions, returning control back to the event loop so other tasks can progress without blocking the thread.
Code Example
python
import asyncio
async def fetch_api(source_id: int):
print(f"Task {source_id} started...")
await asyncio.sleep(1) # Non-blocking async sleep
print(f"Task {source_id} completed!")
return f"Result {source_id}"
async def main():
# Run multiple async operations concurrently
results = await asyncio.gather(
fetch_api(1),
fetch_api(2),
fetch_api(3)
)
print("All tasks finished:", results)
asyncio.run(main()) # Takes ~1 second total instead of 3 seconds!How It Works & Key Takeaways
`asyncio.gather` fires all three coroutines concurrently, finishing all I/O operations in parallel within the time of the longest task.