Advanced Python Tutorial 6: Asynchronous Programming
๐ง What is Asynchronous Programming?
Asynchronous programming allows your program to handle multiple tasks at once, especially useful when dealing with I/O-bound operations such as reading files or calling web APIs. It improves performance and responsiveness.
๐ Sync vs Async
Synchronous: Tasks are executed one after another — the next waits for the current to finish.
Asynchronous: Tasks can be paused and resumed, allowing others to run concurrently, especially during waiting periods.
๐งช Basic Example with asyncio
Let’s demonstrate using Python’s built-in asyncio
module to run two asynchronous tasks.
๐ Full Code Example
import asyncio
async def task(name, delay):
print(f"{name} started")
await asyncio.sleep(delay)
print(f"{name} finished after {delay}s")
async def main():
await asyncio.gather(
task("Task 1", 2),
task("Task 2", 1)
)
asyncio.run(main())
Output: Task 2 finishes first even though it's written after Task 1, because it has a shorter delay.
๐ When to Use Async?
- Making multiple API requests simultaneously
- Reading/writing to files or databases
- Handling web requests in frameworks like FastAPI or aiohttp
✅ Summary
async def
defines an asynchronous function.await
pauses the function until the awaited task completes.asyncio.gather
runs tasks concurrently.
Thank you DARCHUMS TECH for all the amazing tutorials. You are providing quality and exceptional topics.
ReplyDelete