Async Programming
Asyncio Fundamentals
Understanding Asynchronous Programming
- Synchronous vs asynchronous execution
- Blocking vs non-blocking operations
- Concurrency vs parallelism
- Event loop concept
Basic Asyncio
async deffor coroutine functionsawaitkeyword- Running coroutines with
asyncio.run() - Event loop basics
Coroutines
- Creating coroutines
- Calling coroutines
- Coroutine objects
- Coroutine chaining
Async/Await Patterns
Basic Patterns
- Sequential execution with await
- Concurrent execution with
asyncio.gather() - Running tasks concurrently with
asyncio.create_task() - Waiting for multiple coroutines
Error Handling
- Exception handling in async functions
asyncio.wait_for()for timeouts- Cancelling tasks
- Handling task exceptions
Common Patterns
- Producer-consumer pattern
- Rate limiting
- Retry logic
- Background tasks
Concurrent Programming
Tasks and Futures
- Creating tasks
- Task groups
- Future objects
- Waiting for futures
Synchronization Primitives
asyncio.Lockfor mutual exclusionasyncio.Semaphorefor limiting concurrencyasyncio.Eventfor signalingasyncio.Conditionfor complex coordination
Queues
asyncio.Queuefor async queues- Producer-consumer with queues
- Priority queues
- LifoQueue
Working with Synchronous Code
- Running blocking code in executor
asyncio.to_thread()for CPU-bound tasksloop.run_in_executor()for I/O-bound tasks
Interview Questions
- What is the difference between
asyncandawait? - How does asyncio differ from threading?
- When should you use
asyncio.gather()vsasyncio.create_task()? - How do you handle exceptions in async code?
- What is an event loop and how does it work?
Coding Practice
- Write an async function that fetches data from multiple URLs concurrently.
- Implement an async rate limiter using Semaphore.
- Create an async producer-consumer pattern with a queue.
- Write an async function with timeout handling.
- Implement an async retry mechanism for failed operations.
Resources
- Asyncio Documentation: https://docs.python.org/3/library/asyncio.html
- Real Python Async Guide: https://realpython.com/async-io-python/
- Async Patterns: https://docs.python.org/3/library/asyncio-task.html