asyncio Python کا async/await استعمال کرتے ہوئے concurrent I/O کے لیے فریم ورک ہے۔ یہ ایک event loop کے ذریعے ایک single thread پر بہت سے I/O آپریشنز کو تعاون سے چلاتا ہے — اعلیٰ concurrency I/O-bound کام (نیٹ ورک کالز، ویب سرورز) کے لیے موثر ہے threads کے overhead کے بغیر۔
Coroutines کو متعین کرنا اور چلانا
import asyncio
async def fetch_data(id): # an async function = a coroutine
print(f"start {id}")
await asyncio.sleep(1) # await a non-blocking I/O operation (yields control)
print(f"done {id}")
return id
asyncio.run(fetch_data(1)) # run a coroutine from sync code
ایک async def فنکشن ایک coroutine ہے؛ await اسے I/O پوائنٹ پر معطل کرتا ہے، event loop کو دوسرے coroutines چلانے دیتا ہے — پھر جب منتظر آپریشن مکمل ہو تو دوبارہ شروع ہوتا ہے۔
اہم فائدہ: concurrent I/O
# ❌ sequential — total time ≈ 3 seconds
async def slow():
await fetch_data(1) # wait 1s
await fetch_data(2) # then wait 1s
await fetch_data(3) # then wait 1s
# ✅ concurrent — total time ≈ 1 second (all run together)
async def fast():
await asyncio.gather(fetch_data(1), fetch_data(2), fetch_data(3))
asyncio.gather coroutines کو concurrently چلاتا ہے — جبکہ ایک I/O کا انتظار کر رہا ہے، دوسرے آگے بڑھتے ہیں۔ تین 1-سیکنڈ انتظار ~1 سیکنڈ کل میں ملتے ہیں۔ یہ بنیادی قیمت ہے: ایک thread پر بہت سے I/O انتظاریں ملانا۔
Threads سے یہ کیسے مختلف ہے
Threading: OS-managed, preemptive, real threads (GIL-limited for CPU)
asyncio: single thread, COOPERATIVE — coroutines yield at `await` points
→ lighter weight (handle thousands of connections), no thread overhead,
but one CPU-heavy coroutine blocks everything (no preemption)
اہم قاعدہ: event loop کو روکیں نہ
async def bad():
time.sleep(5) # ❌ BLOCKS the whole event loop (sync sleep)
result = heavy_compute() # ❌ CPU work freezes all coroutines
async def good():
await asyncio.sleep(5) # ✅ non-blocking
# offload CPU work to a thread/process pool
await loop.run_in_executor(None, heavy_compute)
کیونکہ یہ تعاون پذیر اور single-threaded ہے، کوئی بھی blocking/CPU-بھاری کال تمام coroutines کو منجمد کر دیتا ہے۔ await-able async APIs استعمال کریں، اور blocking/CPU کام کو executor میں منتقل کریں۔
جہاں asyncio چمکتا ہے
✓ High-concurrency I/O: web servers (FastAPI), web scraping, many API/DB calls,
websockets, real-time apps — thousands of concurrent connections efficiently
✗ CPU-bound work — use multiprocessing instead (asyncio doesn't help)
یہ کیوں اہم ہے
asyncio Python میں اعلیٰ-concurrency I/O کا جدید طریقہ ہے، FastAPI جیسے frameworks کو طاقت دیتا ہے اور ایک single thread پر ہزاروں بیک وقت رابطوں کو موثر طریقے سے سنبھالنے کو فعال بناتا ہے — thread-per-connection سے بہت ہلکا۔
Coroutines، await، gather کے ساتھ concurrent execution، اور خاص طور پر اہم قاعدہ (event loop کو روکیں نہ؛ CPU/blocking کام منتقل کریں) کو سمجھنا performant async Python لکھنے کے لیے ضروری ہے۔
جانچیں کہ کب یہ فٹ بیٹھتا ہے (I/O-bound concurrency) بمقابلہ کب نہیں (CPU-bound → multiprocessing) اسے مؤثر طریقے سے استعمال کرنے کی کلید ہے۔
