asyncio هو إطار عمل Python الخاص بـ concurrent I/O باستخدام async/await. يشغل العديد من عمليات I/O بشكل تعاوني على خيط واحد عبر حلقة الأحداث — فعالة للعمل I/O-bound عالي التزامن (استدعاءات الشبكة، خوادم الويب) دون الحمل الزائد من الخيوط.
asyncio هو إطار عمل Python الخاص بـ concurrent I/O باستخدام async/await. يشغل العديد من عمليات I/O بشكل تعاوني على خيط واحد عبر حلقة الأحداث — فعالة للعمل I/O-bound عالي التزامن (استدعاءات الشبكة، خوادم الويب) دون الحمل الزائد من الخيوط.
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، مما يسمح لحلقة الأحداث بتشغيل coroutines أخرى في هذه الأثناء — ثم تستأنف عندما تكتمل العملية المتوقعة.
# ❌ 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 بشكل متزامن — بينما ينتظر أحدهما I/O، تتقدم الآخرون. ثلاثة انتظارات مدة ثانية واحدة تتداخل إلى حوالي ثانية واحدة إجمالي. هذه هي القيمة الأساسية: تداخل العديد من انتظارات I/O على خيط واحد.
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)
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)
لأنها تعاونية وأحادية الخيط، أي استدعاء حجب/CPU ثقيل يتجمد جميع coroutines. استخدم async APIs قابلة للـ await، وأوكل عمل الحجب/CPU إلى executor.
✓ 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 هو النهج الحديث لـ high-concurrency I/O في Python، يدعم أطر عمل مثل FastAPI ويمكّن من التعامل الفعال مع آلاف الاتصالات المتزامنة على خيط واحد — أخف بكثير من thread-per-connection.
فهم coroutines، await، التنفيذ المتزامن مع gather، والأهم من ذلك القاعدة الأساسية (لا تحجب حلقة الأحداث؛ أوكل عمل CPU/الحجب) ضروري لكتابة async Python أداء جيد.
معرفة متى يناسبها (I/O-bound concurrency) مقابل متى لا (CPU-bound → multiprocessing) هو المفتاح لاستخدامها بفعالية.