Event Loop Architecture & async/await Coroutines
1Concept
`asyncio` achieves concurrency on a single thread using cooperative multitasking managed by an Event Loop. Coroutines defined with `async def` yield control at `await` expressions, allowing other coroutines to execute while waiting for non-blocking I/O.
2Architecture Diagram
Event Loop Running on 1 Thread: [ Coroutine A await socket ] ---> Suspended ---> [ Coroutine B executes ] ---> Socket ready ---> Resumes A
3Code Example
Python 3.12
import asyncio
async def fetch_data(service: str, delay: float) -> str:
print(f"Starting fetch from {service}...")
await asyncio.sleep(delay) # Non-blocking cooperative sleep
return f"{service} Payload"
async def main():
result = await fetch_data("AuthService", 0.05)
print(f"Received: {result}")
asyncio.run(main())4Expected Output
Starting fetch from AuthService... Received: AuthService Payload
5Key Takeaways
- ✓Never use blocking calls (like `time.sleep()` or `requests.get()`) inside coroutines; it blocks the entire event loop.
- ✓Coroutines do NOT run when called (`f()`); they must be awaited or scheduled as a Task.
- ✓`asyncio.run(main())` manages creating and tearing down the event loop.