Day 23: Asynchronous Programming
What Is Asynchronous?
Synchronous code waits until a task completes, while asynchronous code performs other tasks during the wait time.
async/await Basics
import asyncio
async def say_hello(name, delay):
await asyncio.sleep(delay)
print(f"Hello, {name}! (after {delay}s)")
async def main():
# Sequential execution: 3 seconds
await say_hello("Alice", 1)
await say_hello("Bob", 2)
asyncio.run(main())
Concurrent Execution: gather
async def main():
# Concurrent execution: 2 seconds (based on the longest task)
await asyncio.gather(
say_hello("Alice", 1),
say_hello("Bob", 2),
say_hello("Charlie", 1.5),
)
asyncio.run(main())
Synchronous vs Asynchronous Comparison
| Item | Synchronous | Asynchronous |
|---|---|---|
| Keyword | def | async def |
| Call | func() | await func() |
| Waiting | Blocking | Non-blocking |
| I/O tasks | Sequential | Concurrent |
| Best for | CPU computation | Network, file I/O |
Asynchronous HTTP Requests
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.json()
async def fetch_all(urls):
async with aiohttp.ClientSession() as session:
tasks = [fetch(session, url) for url in urls]
results = await asyncio.gather(*tasks)
return results
urls = [
"https://jsonplaceholder.typicode.com/posts/1",
"https://jsonplaceholder.typicode.com/posts/2",
"https://jsonplaceholder.typicode.com/posts/3",
]
results = asyncio.run(fetch_all(urls))
for r in results:
print(r["title"])
Async Context Manager
class AsyncTimer:
def __init__(self, name):
self.name = name
async def __aenter__(self):
self.start = asyncio.get_event_loop().time()
return self
async def __aexit__(self, *args):
elapsed = asyncio.get_event_loop().time() - self.start
print(f"{self.name}: {elapsed:.2f}s")
async def main():
async with AsyncTimer("API call"):
await asyncio.sleep(1)
asyncio.run(main())
Today’s Exercises
- Make 5 URL requests concurrently, measure response times, and compare with sequential execution.
- Use async file reading (
aiofiles) to read multiple files concurrently. - Implement an async producer-consumer pattern using
asyncio.Queue.