Skip to content

Python ناهمگام (Async): asyncio، Event Loop، await، Task، فراخوانی‌های Blocking و Thread Pool ​

"The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses." — مستندات Python، «Event Loop»، docs.python.org/3/library/asyncio-eventloop.html

خلاصه (Summary): asyncio تعداد زیادی کوروتین (Coroutine) را روی ۱ ریسمان (Thread) اجرا می‌کند. فراخوانی تابع async def شیء Coroutine می‌سازد؛ وظیفه (Task) آن را در بر می‌گیرد و روی حلقهٔ رویداد (Event loop) می‌گذارد. وقتی await به چیزی برسد که هنوز آماده نیست، مثل خواندن سوکت، تایمر یا نتیجهٔ آینده (Future)، Task ریسمان را پس می‌دهد. Event loop از سیستم‌عامل می‌پرسد کدام ورودی/خروجی (I/O) آماده است: با انتخاب‌گر آمادگی (Selector) و epoll/kqueue در Unix یا اعلان تکمیل IOCP در حلقهٔ مبتنی بر تکمیل (Proactor) ویندوز. سپس Task آماده را ادامه می‌دهد. await روی نتیجهٔ آماده اصلاً جابه‌جایی ایجاد نمی‌کند؛ await asyncio.sleep(0) واگذاری صریح اجراست. هزاران انتظار شبکه ارزان می‌شوند، اما یک فراخوانی مسدودکننده (Blocking)، مثل time.sleep، requests، راه‌انداز همگام پایگاه داده یا حلقهٔ محاسباتی، همه را معطل می‌کند؛ تا برنگردد، هیچ کار دیگری روی آن حلقه اجرا نمی‌شود. کار Blocking را به مجموعهٔ ریسمان‌ها (Thread pool) می‌سپاریم: asyncio.to_thread، run_in_executor یا run_in_threadpool در Starlette. کار محاسباتی به پردازه‌ها (Processes) می‌رود و قفل سراسری مفسر (GIL) تعیین می‌کند کدام واقعاً موازی اجرا شود. تمرکز (Focus): تفاوت هم‌روندی (Concurrency) و اجرای موازی (Parallelism)، GIL و ساخت بدون GIL (Free-threaded build)، کار منتظر I/O و کار محاسباتی (I/O-bound و CPU-bound)، I/O مسدودکننده و غیرمسدودکننده؛ سازوکار Event loop، Selector، تابع بازخوان (Callback) و uvloop؛ Coroutine، async def، await، شیء قابل انتظار (Awaitable)، Future و Task؛ نگهداری ارجاع create_task، جمع‌کردن نتیجه با gather و return_exceptions، TaskGroup، as_completed و wait با FIRST_COMPLETED؛ لغو (Cancellation) با CancelledError و shield، مهلت (Timeout) با wait_for و asyncio.timeout و هم‌روندی ساخت‌یافته (Structured concurrency) با حوزهٔ لغو (Cancel scope) در AnyIO؛ هماهنگی با Lock، Semaphore، Event، Condition و Queue، الگوی تولیدکننده/مصرف‌کننده (Producer/consumer) و پس‌فشار (Back-pressure)؛ برون‌سپاری (Offload) با to_thread و run_in_executor به Thread pool یا مجموعهٔ پردازه‌ها (Process pool)؛ مولد ناهمگام (Async generator)، مدیر زمینهٔ ناهمگام (Async context manager)، contextvars، حالت اشکال‌زدایی (Debug mode) و هشدارها؛ httpx.AsyncClient و محدودیت اتصال (Connection)، رفتار Uvicorn و Starlette و FastAPI، تست با pytest-asyncio و افزونهٔ AnyIO، خاموشی آرام (Graceful shutdown) و همتاهای Go و PHP. هدف یادگیری (Learning goal): کد Async را بخوانید و بگویید کجا منتظر می‌ماند، هنگام انتظار چه چیز دیگری اجرا می‌شود و چه چیزی حلقه را متوقف می‌کند. فراخوانی‌های I/O را با سقف هم‌روندی و Timeout پخش کنید، برای هر Task ارجاع نگه دارید و هنگام خاموشی درست لغوش کنید، کار Blocking و CPU را به Pool مناسب ببرید و هر ادعا را با تست و اندازه‌گیری ثابت کنید.

موضوع این صفحه مدل هم‌روندی در خود زبان است. قاعدهٔ «Route با async def روی حلقه اجرا می‌شود و Route با def در Thread pool» و نخستین اندازه‌گیری آن در مبانی FastAPI است. راهنمای نوع و Pydantic در Typing و Pydantic v2، AsyncSession و موتور و راه‌انداز Async در SQLAlchemy 2 و SQLModel، و BackgroundTasks و تلاش مجدد و فراخوانی API با httpx در کار پس‌زمینه، Cache و API خارجی هستند. کارگر (Worker) در Uvicorn/Gunicorn، چرخهٔ عمر (Lifespan) در محیط عملیاتی و تنظیم کارایی در FastAPI در Production و وضعیت آمادهٔ تست (Fixture) و چیدمان تست‌ها در تست FastAPI آمده‌اند. دید طراحی شامل Actor، وضعیت مشترک و CSP در طراحی برای هم‌روندی است؛ همتاهای Go در Goroutine و Channel، context، Worker pool و Pipeline و وضعیت رقابتی (Race condition) و Deadlock هستند.

حقایق صفحه با مستندات Python 3.15 دربارهٔ Task، Event loop، Queue، ابزارهای همگام‌سازی، زیرپردازه، توسعه با asyncio، استثنا، Runner و سکوها بررسی شده‌اند. concurrent.futures، contextvars، threading، multiprocessing، selectors، واژه‌نامه، راهنمای Free threading و تغییرات 3.4 تا 3.14 نیز مبنا بوده‌اند؛ همین‌طور PEPهای ۴۹۲، ۵۲۵، ۵۳۰، ۵۶۷، ۶۵۴، ۷۰۳، ۷۷۹ و ۳۱۵۶ و کد CPython 3.9 در asyncio/base_events.py، tasks.py، threads.py و concurrent/futures/thread.py. منابع دیگر عبارت‌اند از مستندات AnyIO 4 دربارهٔ Task، Cancellation، هماهنگی، Thread و تست، README مربوط به uvloop، مستندات httpx دربارهٔ Async و Limits و Timeout و Client، صفحهٔ «Concurrency and async / await» در FastAPI، صفحهٔ Thread pool و concurrency.py در Starlette، تنظیمات Uvicorn، مستندات pytest-asyncio، تور Go و مقالهٔ Pipeline، مستندات Octane در Laravel 13، راهنمای PHP Fibers، ReactPHP و README مربوط به Swoole. صفحه برای Python 3.12+ نوشته شده است؛ قطعه‌کدها با تنها مفسر ماشین ساخت، CPython 3.9.6، اجرا شدند. بنابراین پروژه جدیدترین نسخه‌های قابل نصب روی آن را ثابت کرده است: anyio 4.12.1، httpx 0.28.1، FastAPI 0.128.8، Starlette 0.49.3، Uvicorn 0.39.0 با uvloop 0.23.0، pytest 8.4.2 و pytest-asyncio 1.2.0؛ مجموعهٔ نهایی در requirements.lock است. هر خروجی «واقعی» از همان اجراست. asyncio.TaskGroup و asyncio.timeout() در 3.11 اضافه شدند و در 3.9 وجود ندارند؛ خطای واقعی: AttributeError: module 'asyncio' has no attribute 'TaskGroup'. کدشان پشت بررسی نسخه قرار دارد، ۲ تستشان در 3.9 نادیده‌گرفته‌شده (Skipped) هستند و رفتار مستندشان با برچسب «مورد انتظار، اجرا نشده» آمده است. همان رفتار Structured concurrency با Task group و Cancel scope در AnyIO روی 3.9 واقعاً اجرا شده است.

نقشهٔ صفحه (Page map) ​

اگر دنبال این هستیدبروید به
جدول‌هایی که باید در یک دقیقه حفظ باشیدهمه‌چیز در یک دقیقه
چرا یک Thread می‌تواند 10,000 اتصال را سرویس دهدچرا وجود دارد
Generator، Tulip، async/await، TaskGroup و Free threadingاز کجا آمده
Endpoint داشبورد قبل و بعد از اصلاح با زمان‌هاPython
تفاوت Concurrency و Parallelismهم‌روندی و اجرای موازی
GIL، python3.13t و PYTHON_GILGIL و Python بدون GIL
کدام فراخوانی Blocking استI/O-bound و CPU-bound
selectors، epoll، kqueue و uvloopEvent loop
async def، await، Coroutine، Awaitable و FutureCoroutine و Awaitable
create_task، رهاکردن Task و "Task was destroyed"Taskها
استفاده از gather(..., return_exceptions=True)gather
استفاده از async with asyncio.TaskGroup()TaskGroup
ترتیب تکمیل با as_completed و wait(FIRST_COMPLETED)as_completed و wait
task.cancel()، CancelledError و shieldلغو
wait_for، asyncio.timeout و TimeoutErrorمهلت
Task group در AnyIO، move_on_after و Cancel scopeAnyIO و هم‌روندی ساخت‌یافته
Lock، Semaphore، Event و Conditionابزارهای هماهنگی
asyncio.Queue، maxsize، task_done و joinصف و پس‌فشار
to_thread، run_in_executor و اندازهٔ Executor پیش‌فرضاجرای کد Blocking
ProcessPoolExecutor و multiprocessingکار CPU-bound
async for، async with و @asynccontextmanagerGenerator و Context manager ناهمگام
شناسهٔ درخواست در هر خط Logcontextvars
asyncio.run، run_until_complete و nest_asyncioنقطهٔ ورود و حلقهٔ تودرتو
PYTHONASYNCIODEBUG، Callback کند و "never awaited"اشکال‌زدایی
httpx.AsyncClient، Limits و TimeoutClient ناهمگام HTTP
حلقهٔ Uvicorn، Route با def و run_in_threadpoolرفتار FastAPI و Starlette و Uvicorn
@pytest.mark.asyncio و @pytest.mark.anyioتست Async
توقف Taskها هنگام SIGTERMخاموشی آرام
دسترسی Async به پایگاه داده و راه‌انداز Syncپایگاه داده در کد Async
پیش‌برد Coroutine توسط Task، متن خطا و ماتریس نسخه‌هاسازوکار
باگ‌های کلاسیک و اصلاحشانحل مسائل رایج
انتخاب بین asyncio، Thread، Process و Goانتخاب
از Monolith تا سیستم توزیع‌شدهدر معماری
بازتولید همهٔ اندازه‌گیری‌هاآزمایشگاه
Swoole، Octane، ReactPHP و Fiberبرای توسعه‌دهندگان PHP/Laravel
Goroutine در برابر Task و Channel در برابر Queueنگاه Go

همه‌چیز در یک دقیقه (One minute) ​

واژگان در یک جدول. هر ردیف در فهرست مفاهیم باز می‌شود.

اصطلاحچیستبه زبان سادهAPI در Python
تابع کوروتین (Coroutine function)تابع تعریف‌شده با async def«دستور پختی که می‌تواند مکث کند»async def fetch(): ...
کوروتین (Coroutine)خروجی فراخوانی تابع؛ فقط با await یا Task اجرا می‌شود«دستور پخت متوقف، هنوز شروع نشده»fetch()
awaitتعلیق Coroutine تا پایان Awaitable«اینجا منتظر باش، بقیه اجرا شوند»await fetch()
قابل انتظار (Awaitable)Coroutine، Task، Future یا شیء دارای __await__ که await می‌پذیرد«چیزی که می‌شود منتظرش ماند»inspect.isawaitable
نتیجهٔ آینده (Future)جای خالی سطح پایین برای نتیجه‌ای که بعداً تعیین می‌شود«جعبهٔ خالی که کسی پر می‌کند»loop.create_future()
وظیفه (Task)Futureای که Coroutine را روی حلقه پیش می‌برد«دستور پخت در حال اجرا در آشپزخانه»asyncio.create_task(coro)
حلقهٔ رویداد (Event loop)زمان‌بند: Timer، Callback آماده و Selector«یک پیشخدمت»asyncio.get_running_loop()
انتخاب‌گر آمادگی (Selector)API آمادگی سیستم‌عامل در SelectorEventLoop: epoll، kqueue، poll، select«کدام میز دست بلند کرده؟»selectors.DefaultSelector
حلقهٔ مبتنی بر تکمیل (Proactor)حلقهٔ Windows با IOCP؛ سیستم‌عامل پایان عملیات را خبر می‌دهد، نه آمادگی سوکت را«وقتی غذا آماده شد خبر بده»asyncio.ProactorEventLoop
فراخوانی مسدودکننده (Blocking call)Thread را تا بازگشت در اختیار می‌گیرد«پیشخدمت گیرکرده کنار یک میز»time.sleep، requests.get
مجموعهٔ ریسمان‌ها (Thread pool)Threadهای Worker برای فراخوانی Blocking«کمک‌آشپزها»asyncio.to_thread، run_in_executor
مجموعهٔ پردازه‌ها (Process pool)Processهای Worker برای کار CPU«آشپزخانهٔ دیگر»ProcessPoolExecutor
قفل سراسری مفسر (GIL)در CPython پیش‌فرض فقط یک Thread در هر لحظه Bytecode اجرا می‌کند«یک قلم برای همهٔ کارمندها»sys._is_gil_enabled() از 3.13+

برای هر انتظار چه ابزاری؟ همهٔ عددها از آزمایشگاه با CPython 3.9.6 روی Mac ۱۲ هسته‌ای هستند.

کارمثالابزار مناسبانتخاب دیگر چه مشکلی دارداندازه‌گیری
I/O شبکه با کتابخانهٔ Asynchttpx.AsyncClient، asyncpg، redis.asyncioawait + gather/TaskGroupمشکلی ندارد؛ کاربرد اصلی همین است20 × 100 ms در 0.14 s
I/O شبکه با کتابخانهٔ Syncrequests، httpx.Client، boto3، راه‌انداز Sync پایگاه دادهasyncio.to_thread یا Route با defدر async def ترتیبی می‌شود و حلقه را می‌بندد2.07 s؛ انتظار /health برابر 0.55 s
خواب یا عقب‌نشینی (Backoff)تأخیر تلاش مجددawait asyncio.sleeptime.sleep همهٔ Taskها را متوقف می‌کندفاصلهٔ Heartbeat: 0.211 s در برابر 0.013 s
I/O فایل و sqlite3خواندن گزارش، پایگاه دادهٔ محلیto_threadحلقه را می‌بندداجرای کد Blocking
CPU در Python خالصتجزیه، قیمت‌گذاری، پردازش تصویر در PythonProcessPoolExecutorThread به‌خاطر GIL سریع‌تر نمی‌شود4 کار: مستقیم 0.42 s، Threadها 0.37 s، Processها 0.18 s
افزونهٔ C که GIL را آزاد می‌کندhashlib، zlib، NumPyThread poolمشکلی ندارد؛ Threadها موازی اجرا می‌شونداندازه‌گیری نشده
فراخوانی هم‌زمان بیش‌ازحد10,000 URLSemaphore یا Queue محدودمصرف سوکت و حافظه و فشار روی سرویس بالادستSemaphore(5): 0.44 s در 4 موج

ترکیب‌کننده‌ها (Combinators). خروجی چیست و چه کسی چه کاری را لغو می‌کند؟

APIخروجیهنگام اولین خطاهنگام Timeoutدیگران را لغو می‌کند؟از نسخهٔ
await gather(*aws)فهرست به ترتیب ورودیخطا را پرتاب می‌کند؛ بقیه ادامه می‌دهندنداردنه؛ فقط اگر خود gather لغو شود3.4
gather(*aws, return_exceptions=True)فهرست با استثنا به‌عنوان مقدارچیزی پرتاب نمی‌شودنداردنه3.4
async with TaskGroup()نتیجه در Taskهالغو هم‌گروهی‌ها و ExceptionGroupهمراه timeout()بله3.11
as_completed(aws)Iterator به ترتیب تکمیلهنگام await همان عضوTimeoutErrorنه3.4؛ پیمایش Async از 3.13
wait(aws, return_when=...)مجموعه‌های (done, pending)FIRST_EXCEPTION زود برمی‌گرددبازگشت بدون خطانه3.4
wait_for(aw, t)نتیجهخطا را پرتاب می‌کندTimeoutError و لغو Awaitable داخلیبله، Awaitable داخلی3.4
async with timeout(t)بلوکخطا را پرتاب می‌کندTimeoutError و لغو بلوکبله، کار Task جاری3.11
shield(aw)نتیجهخطا را پرتاب می‌کندنداردداخلی را از لغو بیرونی حفظ می‌کند3.4

وقتی چیزی خراب است چه چاپ می‌شود؟ خروجی واقعی اجرای قطعه‌کدهاست.

اشتباهخروجیکجا
فراخوانی تابع Coroutine بدون awaitRuntimeWarning: coroutine 'forgotten' was never awaitedهمیشه در stderr
شکست Task بدون خواندن نتیجهTask exception was never retrievedLogger با نام asyncio، هنگام جمع‌آوری حافظه
بستن حلقه با Task معلقTask was destroyed but it is pending!Logger با نام asyncio
نگه‌داشتن حلقه بیش از 100 ms در CallbackExecuting <Task pending name='Task-1' ...> took 0.213 secondsLogger با نام asyncio، فقط Debug mode
asyncio.run() داخل حلقهٔ در حال اجراRuntimeError: asyncio.run() cannot be called from a running event loopاستثنا
asyncio.TaskGroup روی 3.9/3.10AttributeError: module 'asyncio' has no attribute 'TaskGroup'استثنا

چرا وجود دارد (Why it exists) ​

بیشتر عمر Backend در انتظار می‌گذرد: ردیف پایگاه داده، پاسخ HTTP بالادست، پاسخ Redis یا Client کندخوان. ۱ ریسمان (Thread) برای هر اتصال (Connection)، نوشتن انتظار را ساده می‌کند، اما هر Thread پشته و ورودی زمان‌بند می‌خواهد و در CPython باید نوبت GIL بگیرد. ده‌ها هزار Thread عمدتاً بیکار گران‌اند. حلقهٔ رویداد (Event loop) مدل را برعکس می‌کند: ۱ Thread فهرست همهٔ انتظارها را نگه می‌دارد، با یک فراخوانی از سیستم‌عامل می‌پرسد کدام تمام شده و فقط کد آماده را اجرا می‌کند. هدف نحو جدید در PEP ۴۹۲ چنین بیان شده است: "The growth of Internet and general connectivity has triggered the proportionate need for responsive and scalable code. This proposal aims to answer that need by making writing explicitly asynchronous, concurrent Python code easier and more Pythonic."

Thread برای هر درخواست؛ WSGI، PHP-FPM و Route با defEvent loop؛ asyncio و Route با async def
سیستم‌عامل می‌تواند اجرای Thread را در هر دستور جابه‌جا کند؛ پیش‌دستانه (Preemptive)Task فقط در await تعلیق‌کننده جابه‌جا می‌شود؛ مشارکتی (Cooperative)
فراخوانی Blocking یک Thread را می‌بنددفراخوانی Blocking همهٔ Taskهای حلقه را می‌بندد
حافظهٔ انتظار هر درخواست: پشتهٔ Threadحافظهٔ انتظار هر درخواست: Frame مربوط به Coroutine و یک Task
وضعیت مشترک همه‌جا قفل می‌خواهدبین دو await وضعیت مشترک امن است؛ قفل دور awaitها لازم می‌شود
هر کتابخانه‌ای قابل استفاده استکتابخانه باید Async باشد یا به Thread برون‌سپاری شود
سقف Concurrency تعداد Threadهاست؛ FastAPI: 40 توکنسقف Concurrency سوکت، حافظه و محدودیت خودتان است
CPU موازی با Thread، اگر GIL اجازه بدهدروی حلقه CPU موازی نداریم؛ Process لازم است

تصویری روزمره. رستوران ۱ پیشخدمت، یعنی Event loop، و ۱ آشپزخانه دارد. پیشخدمت سفارش میز اول را می‌گیرد، تحویل آشپزخانه می‌دهد و به‌جای ایستادن تا آماده‌شدن غذا، سراغ میز دوم می‌رود؛ این همان await است. زنگ که به صدا درآمد، یعنی Selector آمادگی سوکت را اعلام کرد، غذا را تحویل می‌گیرد. ۱ نفر ۵۰ میز را پوشش می‌دهد چون بیشتر زمان صرف پختن می‌شود، نه رفت‌وآمد. شرطش این است که خودش هیچ کار آهسته‌ای انجام ندهد. اگر بنشیند سیب‌زمینی پوست بکند، مانند time.sleep یا راه‌انداز Sync یا حلقهٔ CPU، همهٔ میزها منتظر می‌مانند؛ حتی میزهایی که غذایشان آماده است. کار دستی کند را کمک‌آشپزهای Thread pool می‌گیرند. کاری که واقعاً نیروی بیشتر می‌خواهد، مثل پخت ۱۰۰ کیک، به آشپزخانهٔ دوم با کارکنان مستقل، یعنی Process pool، می‌رود؛ کمک‌آشپزهای همین آشپزخانه ۱ فر مشترک، یعنی GIL، دارند. دفتر رزرو با سقف ۱۰ میز Semaphore است؛ جای سفارش با ظرفیت ۵ برگه Queue محدود؛ پیشخدمتی که از میز بیش‌ازحد معطل‌کننده می‌گذرد Timeout؛ مدیری که با مشکل یک مهمان همهٔ گروه را مرخص می‌کند TaskGroup است.

۳ بدفهمی رایج از همان ابتدا ​

۱. «async def کد را موازی اجرا می‌کند.» امکان انتظار هم‌روند می‌دهد. در هر لحظه فقط ۱ Coroutine روی حلقه اجرا می‌شود؛ برای CPU، Async سربار اضافه می‌کند و سرعتی نمی‌دهد. اندازه‌گیری‌شده: ۲۰ درخواست ۱۰۰ میلی‌ثانیه‌ای ترتیبی ۲٫۰۷ ثانیه طول کشیدند؛ همان ۲۰ درخواست با Client همگام داخل async def و زیر gather() نیز ۲٫۰۷ ثانیه شدند، چون هیچ awaitی نبود. ۲. «فراخوانی تابع Coroutine آن را شروع می‌کند.» فقط شیء می‌سازد. بدون await یا create_task اجرا نمی‌شود و هنگام جمع‌آوری شیء، Python پیام coroutine '...' was never awaited می‌دهد. ۳. «create_task() را صدا بزن و فراموش کن.» حلقه فقط ارجاع ضعیف (Weak reference) نگه می‌دارد؛ مستندات دربارهٔ Task بدون ارجاع می‌گویند "may get garbage collected at any time, even before it's done". استثناهایش هم دیده نمی‌شوند. Taskها را در Set یا TaskGroup نگه دارید.

از کجا آمده (Where it comes from) ​

کوروتین (Coroutine) در Python از مولد (Generator) رشد کرد. yield امکان مکث تابع را می‌داد؛ PEP ۳۴۲ در ۲۰۰۵-۰۵-۱۰ برای Python 2.5 ایجاد شد و با send() امکان فرستادن مقدار به تابع را افزود؛ همین سازوکار پایهٔ زمان‌بندهای Coroutine شد. PEP ۳۸۰ در ۲۰۰۹-۰۲-۱۳ برای Python 3.3، yield from را برای واگذاری کار به Generator دیگر افزود. PEP ۳۱۵۶ نوشتهٔ Guido van Rossum در ۲۰۱۲-۱۲-۱۲، Event loop و Transport و Protocol و Coroutineهای asyncio را تعریف کرد: "A reference implementation exists under the code name Tulip". Python 3.4 در ۱۶ مارس ۲۰۱۴ آن را با عنوان "New provisional API for asynchronous IO (PEP ۳۱۵۶)" عرضه کرد. آن زمان Coroutine هنوز Generator با @asyncio.coroutine و yield from بود. PEP ۴۹۲ در ۲۰۱۵-۰۴-۰۹ برای Python 3.5 ایجاد شد؛ انتشار ۱۳ سپتامبر ۲۰۱۵، async def، await، async for و async with را آورد و «Native coroutine» را به یک نوع مستقل تبدیل کرد. PEP ۵۲۵ و PEP ۵۳۰ در 3.6 به‌ترتیب Async generator و Async comprehension را افزودند. Python 3.7 در ۲۰۱۸-۰۶-۲۷، async و await را کلمهٔ رزروشده کرد و asyncio.run() و contextvars را آورد؛ PEP ۵۶۷ می‌گوید "similar to thread-local storage (TLS), but, unlike TLS, it also allows correctly keeping track of values per asynchronous task". در 3.8، منتشرشده در ۲۰۱۹-۱۰-۱۴: "The exception asyncio.CancelledError now inherits from BaseException rather than Exception". نسخهٔ 3.9 در ۲۰۲۰-۱۰-۰۵، asyncio.to_thread() را افزود. نسخهٔ 3.11 در ۲۰۲۲-۱۰-۲۴، TaskGroup با توصیهٔ "For new code this is recommended over using create_task() and gather() directly"، timeout() با توصیهٔ "recommended over using wait_for() directly"، Runner، Barrier و همچنین ExceptionGroup و except* از PEP ۶۵۴ را آورد. نسخهٔ 3.12 در ۲ اکتبر ۲۰۲۳، Eager task factory را افزود و گزارش کرد: "The asyncio package has had a number of performance improvements, with some benchmarks showing a 75% speed up". نسخهٔ 3.13 در ۷ اکتبر ۲۰۲۴، Queue.shutdown()، پیمایش Async روی as_completed() و ساخت آزمایشی Free-threaded با PEP ۷۰۳ را عرضه کرد. نسخهٔ 3.14 در ۲۰۲۵-۱۰-۰۷ پشتیبانی رسمی Free threading را با PEP ۷۷۹، مصوب ۲۰۲۵-۰۶-۱۶، افزود؛ فرمان‌های python -m asyncio ps PID و pstree PID برای مشاهدهٔ Taskها آمدند و سیستم Policy منسوخ شد: "will be removed in Python 3.16". نسخهٔ 3.15، منتشرشده در ۹ اکتبر ۲۰۲۶ و مبنای مستندات نقل‌شده، TaskGroup.cancel() را افزود.

بیرون کتابخانهٔ استاندارد، uvloop از MagicStack با توصیف "a fast, drop-in replacement of the built-in asyncio event loop … implemented in Cython and uses libuv under the hood"، هر جا نصب باشد حلقهٔ پیش‌فرض Uvicorn شد. AnyIO، با بارگذاری 1.0.0 در PyPI در ۲۰۱۹-۰۵-۱۴، هم‌روندی ساخت‌یافته (Structured concurrency) به سبک Trio را به asyncio آورد؛ Starlette و FastAPI بر پایهٔ آن ساخته شده‌اند.

1  2005  PEP 342 created (Python 2.5): generators that receive values with send() = the coroutine mechanism
2  2012  PEP 3156 "Tulip" created (2012-12-12); PEP 380 (2009, Python 3.3) had added yield from
3  2014  Python 3.4 (2014-03-16): asyncio, provisional; @asyncio.coroutine + yield from
4  2015  Python 3.5 (2015-09-13): PEP 492 async def / await / async with / async for
5  2016  PEP 525 async generators and PEP 530 async comprehensions created (Python 3.6)
6  2018  Python 3.7 (2018-06-27): asyncio.run(), contextvars (PEP 567), async/await reserved keywords
7  2019  Python 3.8 (2019-10-14): CancelledError becomes a BaseException; AnyIO 1.0.0
8  2020  Python 3.9 (2020-10-05): asyncio.to_thread()
9  2022  Python 3.11 (2022-10-24): TaskGroup, timeout(), Runner, Barrier, ExceptionGroup / except*
10 2023  Python 3.12 (2023-10-02): asyncio up to 75% faster on some benchmarks, eager tasks
11 2024  Python 3.13 (2024-10-07): Queue.shutdown, async-iterable as_completed, free-threaded build (experimental)
12 2025  Python 3.14 (2025-10-07): free threading officially supported (PEP 779), asyncio ps / pstree, policies deprecated
13 2026  Python 3.15 (2026-10-09): TaskGroup.cancel() for an early, non-exceptional exit

Python ​

قبل (Before) ​

یک نقطهٔ پایانی (Endpoint) داشبورد ۵ بخش سفارش، صورتحساب، تیکت، محموله و نظر را از سرویس داخلی می‌گیرد؛ هر پاسخ ۱۰۰ ms زمان می‌برد. تابع async def است و غیرمسدودکننده به نظر می‌رسد، اما داخلش httpx.Client همگام درخواست‌ها را یکی‌یکی می‌فرستد، با time.sleep «رندر» می‌کند، با asyncio.create_task() ۱ Task ثبت ممیزی می‌سازد و ارجاعش را دور می‌اندازد؛ آن Task هم CancelledError را می‌بلعد.

py
"""BEFORE: a dashboard endpoint that looks async but blocks the event loop.

Bad design, not broken code: it returns the right JSON on a quiet day.
- a sync HTTP client (httpx.Client) called inside `async def`: one upstream call at a time,
  and the whole loop (every other request) waits with it;
- time.sleep() to "render" inside `async def`;
- fire-and-forget asyncio.create_task() with no reference kept and no error handling;
- CancelledError swallowed in the audit task, so shutdown cannot stop it cleanly.
"""
from __future__ import annotations

import asyncio
import time

import httpx
from fastapi import FastAPI

SECTIONS = ["orders", "invoices", "tickets", "shipments", "reviews"]


def create_app(upstream: str, delay_ms: int = 100) -> FastAPI:
    app = FastAPI(title="dashboard (before)")
    audit_log: list[str] = []
    app.state.audit_log = audit_log

    async def write_audit(user: str) -> None:
        try:
            await asyncio.sleep(0.01)
            audit_log.append(user)
        except asyncio.CancelledError:
            pass  # swallowed: the task reports success even when it was cancelled

    @app.get("/health")
    async def health() -> dict[str, str]:
        return {"status": "ok"}

    @app.get("/dashboard/{user}")
    async def dashboard(user: str) -> dict[str, object]:
        data = {}
        with httpx.Client(base_url=upstream, trust_env=False) as client:  # sync client
            for section in SECTIONS:
                data[section] = client.get(f"/delay/{delay_ms}").json()  # blocks the loop
        time.sleep(0.05)  # "render a chart": blocks the loop again
        asyncio.create_task(write_audit(user))  # no reference kept, errors never seen
        return {"user": user, "sections": data}

    return app

بعد (After) ​

همان Endpoint اکنون سرتاسر ناهمگام (Async) است: یک httpx.AsyncClient برای هر Process در Lifespan باز می‌شود و Limits و Timeout صریح دارد؛ ۵ فراخوانی با gather() زیر Semaphore پخش می‌شوند و هرکدام wait_for دارند. پایان مهلت بالادست پاسخ 504 می‌دهد، رندر Blocking به asyncio.to_thread() می‌رود، Task ممیزی در Set قابل پیگیری می‌ماند و هنگام خاموشی تخلیه می‌شود. یک Route با def و یک فراخوانی run_in_threadpool هم نشان می‌دهند FastAPI و Starlette کد Sync را کجا اجرا می‌کنند.

py
"""AFTER: the same endpoint, async end to end, bounded, with timeouts and a clean shutdown.

- one httpx.AsyncClient per process, opened in the lifespan, with explicit connection limits;
- upstream calls fanned out with gather() under a Semaphore, each with a timeout;
- the blocking "render" step moved to a worker thread with asyncio.to_thread();
- background work tracked in a set (strong references) and drained on shutdown;
- a plain `def` route for a blocking library: FastAPI runs it in the AnyIO thread pool.
"""
from __future__ import annotations

import asyncio
import logging
import threading
import time
from contextlib import asynccontextmanager
from typing import AsyncIterator

import httpx
from fastapi import FastAPI, HTTPException
from starlette.concurrency import run_in_threadpool

from app.tasks import BackgroundTasks

log = logging.getLogger(__name__)

SECTIONS = ["orders", "invoices", "tickets", "shipments", "reviews"]


def render_chart(data: dict[str, object]) -> int:
    time.sleep(0.05)  # stands in for a blocking library (PDF, image, legacy SDK)
    return len(data)


def create_app(upstream: str, delay_ms: int = 100, max_in_flight: int = 10, timeout_s: float = 1.0) -> FastAPI:
    @asynccontextmanager
    async def lifespan(app: FastAPI) -> AsyncIterator[None]:
        limits = httpx.Limits(max_connections=max_in_flight, max_keepalive_connections=max_in_flight)
        timeout = httpx.Timeout(timeout_s, connect=0.5)
        async with httpx.AsyncClient(base_url=upstream, limits=limits, timeout=timeout, trust_env=False) as client:
            app.state.client = client
            app.state.sem = asyncio.Semaphore(max_in_flight)
            app.state.background = BackgroundTasks()
            app.state.audit_log = []
            yield
            # Graceful shutdown: give background tasks 2 s, then cancel what is left.
            app.state.cancelled_on_shutdown = await app.state.background.drain(timeout=2.0)
            if app.state.background.errors:  # failures were logged one by one; summarise too
                log.error("%d background task(s) failed during this run", len(app.state.background.errors))

    app = FastAPI(title="dashboard (after)", lifespan=lifespan)

    async def write_audit(user: str) -> None:
        await asyncio.sleep(0.01)
        app.state.audit_log.append(user)

    async def fetch_section(section: str) -> object:
        async with app.state.sem:  # bound the fan-out, whatever the number of sections
            response = await asyncio.wait_for(app.state.client.get(f"/delay/{delay_ms}"), timeout_s)
            response.raise_for_status()
            return response.json()

    @app.get("/health")
    async def health() -> dict[str, object]:
        # Background failures are visible to monitoring, not only in the logs.
        return {"status": "ok", "background_errors": len(app.state.background.errors)}

    @app.get("/dashboard/{user}")
    async def dashboard(user: str) -> dict[str, object]:
        try:
            results = await asyncio.gather(*(fetch_section(s) for s in SECTIONS))
        except (asyncio.TimeoutError, httpx.HTTPError) as exc:
            raise HTTPException(status_code=504, detail=f"upstream: {type(exc).__name__}") from exc
        data = dict(zip(SECTIONS, results))
        charts = await asyncio.to_thread(render_chart, data)  # loop stays free meanwhile
        app.state.background.spawn(write_audit(user), name=f"audit:{user}")
        return {"user": user, "sections": data, "charts": charts}

    @app.get("/report")
    def report() -> dict[str, str]:
        # `def`, not `async def`: FastAPI calls it via the AnyIO worker-thread pool (40 tokens).
        time.sleep(0.05)
        return {"thread": threading.current_thread().name}

    @app.get("/legacy")
    async def legacy() -> dict[str, str]:
        # Inside `async def`, Starlette's helper offloads one blocking call explicitly.
        name = await run_in_threadpool(lambda: threading.current_thread().name)
        return {"thread": name}

    return app

ابزار پیگیری Task که after.py استفاده می‌کند، همراه مثال‌های Task است: ارجاع قوی، جمع‌کردن خطا و تخلیه با Timeout.

py
"""Tasks vs coroutines, fire-and-forget done right, gather / as_completed / wait / TaskGroup."""
from __future__ import annotations

import asyncio
import logging
import sys
from typing import Any, Awaitable, Callable

log = logging.getLogger(__name__)


async def step(name: str, delay: float, fail: bool = False) -> str:
    await asyncio.sleep(delay)
    if fail:
        raise ValueError(f"{name} failed")
    return name


class BackgroundTasks:
    """Keeps a strong reference to every fire-and-forget task.

    The event loop holds only weak references to tasks, so a task nobody references can be
    garbage collected before it finishes. The set below is the pattern from the asyncio docs,
    plus logging of failures and a drain() for graceful shutdown.
    """

    def __init__(self) -> None:
        self._tasks: set[asyncio.Task[Any]] = set()
        self.errors: list[BaseException] = []

    def spawn(self, coro: Awaitable[Any], *, name: str | None = None) -> asyncio.Task[Any]:
        task = asyncio.ensure_future(coro)
        if name:
            task.set_name(name)
        self._tasks.add(task)
        task.add_done_callback(self._done)
        return task

    def _done(self, task: asyncio.Task[Any]) -> None:
        self._tasks.discard(task)
        if task.cancelled():
            return
        exc = task.exception()
        if exc is not None:
            # Retrieving the exception silences asyncio's "Task exception was never retrieved"
            # report, so the owner MUST report it itself: log it with the traceback and keep it.
            log.error("background task %s failed", task.get_name(), exc_info=exc)
            self.errors.append(exc)

    def __len__(self) -> int:
        return len(self._tasks)

    async def drain(self, timeout: float) -> int:
        """Graceful shutdown: wait up to `timeout`, then cancel the rest. Returns #cancelled."""
        if not self._tasks:
            return 0
        _, pending = await asyncio.wait(set(self._tasks), timeout=timeout)
        for task in pending:
            task.cancel()
        await asyncio.gather(*pending, return_exceptions=True)
        return len(pending)


async def create_task_starts_immediately() -> list[str]:
    """create_task() schedules the coroutine; it starts at the next await of the caller."""
    order: list[str] = []

    async def child() -> None:
        order.append("child runs")

    task = asyncio.create_task(child())
    order.append("after create_task")  # child has not run yet: we have not yielded
    await asyncio.sleep(0)
    order.append("after first await")
    await task
    return order


async def gather_fail_fast() -> tuple[str, list[str]]:
    """return_exceptions=False: first error propagates, the others keep running."""
    finished: list[str] = []

    async def tracked(name: str, delay: float, fail: bool = False) -> str:
        result = await step(name, delay, fail)
        finished.append(name)
        return result

    try:
        await asyncio.gather(tracked("a", 0.01, fail=True), tracked("b", 0.05))
        outcome = "no error"
    except ValueError as exc:
        outcome = str(exc)
    await asyncio.sleep(0.08)  # "b" was NOT cancelled by the failure of "a"
    return outcome, finished


async def gather_collect() -> list[Any]:
    """return_exceptions=True: exceptions come back as values in input order."""
    return await asyncio.gather(
        step("a", 0.02), step("b", 0.01, fail=True), step("c", 0.0), return_exceptions=True
    )


async def first_finished_order() -> list[str]:
    """as_completed() yields results in completion order, not input order."""
    order = []
    for next_done in asyncio.as_completed([step("slow", 0.05), step("fast", 0.01), step("mid", 0.03)]):
        order.append(await next_done)
    return order


async def race_first_completed() -> tuple[str, int]:
    """wait(FIRST_COMPLETED) returns (done, pending); cancelling the losers is YOUR job."""
    tasks = {asyncio.create_task(step(n, d)) for n, d in (("replica-a", 0.05), ("replica-b", 0.01))}
    done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
    for task in pending:
        task.cancel()
    await asyncio.gather(*pending, return_exceptions=True)
    return done.pop().result(), sum(t.cancelled() for t in pending)


async def taskgroup_fail_fast() -> tuple[list[str], list[str]]:
    """Python 3.11+: one failure cancels the siblings and raises an ExceptionGroup."""
    if sys.version_info < (3, 11):  # pragma: no cover - documented, run on 3.11+ only
        raise RuntimeError("asyncio.TaskGroup needs Python 3.11+")
    cancelled: list[str] = []

    async def slow(name: str) -> str:
        try:
            await asyncio.sleep(1)
            return name
        except asyncio.CancelledError:
            cancelled.append(name)
            raise

    try:
        async with asyncio.TaskGroup() as tg:  # type: ignore[attr-defined]
            tg.create_task(slow("b"))
            tg.create_task(slow("c"))
            tg.create_task(step("a", 0.01, fail=True))
    except Exception as eg:  # an ExceptionGroup; `except* ValueError` needs 3.11 syntax
        messages = [str(e) for e in eg.exceptions]  # type: ignore[attr-defined]
        return messages, sorted(cancelled)
    return [], cancelled


async def bounded_gather(funcs: list[Callable[[], Awaitable[Any]]], limit: int) -> list[Any]:
    """gather() with at most `limit` in flight: the classic Semaphore fan-out."""
    sem = asyncio.Semaphore(limit)

    async def run(fn: Callable[[], Awaitable[Any]]) -> Any:
        async with sem:
            return await fn()

    return await asyncio.gather(*(run(f) for f in funcs))

تست هر ۲ برنامه را با httpx.ASGITransport روی Event loop خود اجرا می‌کند؛ /dashboard را می‌فرستد و ۲۰ ms بعد /health را، سپس زمان دیده‌شده از Client را می‌سنجد. خروجی واقعی قبل: /dashboard 0.574s, /health during it 0.554s؛ بعد: /dashboard 0.158s, /health during it 0.002s. بررسی سلامت که کاری نمی‌کند در برنامهٔ قبل ۰٫۵ ثانیه منتظر ماند، چون حلقه در Handler داشبورد گیر کرده بود.

py
from __future__ import annotations

import asyncio
import time
from typing import Any

import httpx
import pytest
from fastapi.testclient import TestClient

from app import after, before


async def dashboard_and_health(app: Any) -> tuple[float, float]:
    """Fire /dashboard, then /health 20 ms later, on the same event loop as the app."""
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://app") as client:

        async def timed(path: str, wait: float) -> float:
            t0 = time.perf_counter()
            await asyncio.sleep(wait)  # a blocked loop also delays this wake-up
            assert (await client.get(path)).status_code == 200
            return time.perf_counter() - t0 - wait  # latency as the client sees it

        return tuple(await asyncio.gather(timed("/dashboard/ana", 0), timed("/health", 0.02)))  # type: ignore[return-value]


@pytest.mark.asyncio
async def test_before_blocks_every_request(upstream: str) -> None:
    app = before.create_app(upstream)
    dash, health = await dashboard_and_health(app)
    print(f"\nBEFORE: /dashboard {dash:.3f}s, /health during it {health:.3f}s")
    assert dash >= 0.5  # 5 x 100 ms one after another + 50 ms render
    assert health >= 0.3  # /health waited for the blocked loop


@pytest.mark.asyncio
async def test_after_keeps_the_loop_free(upstream: str) -> None:
    app = after.create_app(upstream)
    async with app.router.lifespan_context(app):  # ASGITransport does not run the lifespan
        dash, health = await dashboard_and_health(app)
        await asyncio.sleep(0.05)
        assert app.state.audit_log == ["ana"]
    print(f"\nAFTER: /dashboard {dash:.3f}s, /health during it {health:.3f}s")
    assert dash < 0.4  # 5 overlapped calls (~100 ms) + render in a thread (~50 ms)
    assert health < 0.05  # answered while the dashboard was waiting


def test_after_def_route_runs_in_worker_thread(upstream: str) -> None:
    with TestClient(after.create_app(upstream)) as client:
        assert client.get("/report").json()["thread"].startswith("AnyIO worker thread")
        assert client.get("/legacy").json()["thread"].startswith("AnyIO worker thread")


def test_after_upstream_timeout_is_a_504(upstream: str) -> None:
    app = after.create_app(upstream, delay_ms=500, timeout_s=0.1)
    with TestClient(app) as client:
        response = client.get("/dashboard/ana")
    assert response.status_code == 504
    assert response.json()["detail"].startswith("upstream: ")


def test_after_shutdown_drains_background_tasks(upstream: str) -> None:
    app = after.create_app(upstream)
    with TestClient(app) as client:
        assert client.get("/dashboard/bo").status_code == 200
    assert app.state.cancelled_on_shutdown == 0
    assert app.state.audit_log == ["bo"]

بالادست یک سرور ۶۰ خطی HTTP/1.1 با asyncio.start_server است: Keep-alive، پورت موقت و حلقهٔ مستقل در Thread پس‌زمینه. همین ماژول ۵ راهبرد Client برای اندازه‌گیری Fan-out را دارد:

py
"""Sync vs async fan-out against a local test server: the measurement used on the page.

The server is written with asyncio streams (asyncio.start_server), answers GET /delay/<ms>
after sleeping <ms> milliseconds, supports HTTP/1.1 keep-alive and runs on its own event loop
in a background thread, so both sync and async clients can call it.

Run:  python -m app.fanout        (prints the timing table)
"""
from __future__ import annotations

import asyncio
import concurrent.futures
import contextlib
import threading
import time
from typing import Callable, Iterator

import httpx


async def _handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    try:
        while True:
            request_line = await reader.readline()
            if not request_line:
                break  # client closed the keep-alive connection
            while (await reader.readline()) not in (b"\r\n", b"\n", b""):
                pass  # skip headers; GET has no body here
            path = request_line.split()[1].decode()
            ms = int(path.rsplit("/", 1)[-1]) if path.startswith("/delay/") else 0
            await asyncio.sleep(ms / 1000)  # the "slow upstream": waits without blocking
            body = f'{{"slept_ms": {ms}}}'.encode()
            writer.write(
                b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n"
                + f"content-length: {len(body)}\r\n\r\n".encode()
                + body
            )
            await writer.drain()  # flow control: wait if the socket buffer is full
    except (ConnectionResetError, asyncio.IncompleteReadError):
        pass
    finally:
        writer.close()


@contextlib.contextmanager
def serve_in_thread() -> Iterator[str]:
    """Start the test server on an ephemeral port; yield its base URL."""
    loop = asyncio.new_event_loop()
    started = threading.Event()
    holder: dict[str, object] = {}

    async def start() -> None:
        server = await asyncio.start_server(_handle, "127.0.0.1", 0, backlog=512)
        holder["server"] = server
        holder["port"] = server.sockets[0].getsockname()[1]
        started.set()

    def run() -> None:
        asyncio.set_event_loop(loop)
        loop.run_until_complete(start())  # the 3.6-era API: drive one coroutine to completion
        loop.run_forever()

    thread = threading.Thread(target=run, name="test-upstream", daemon=True)
    thread.start()
    started.wait(5)
    try:
        yield f"http://127.0.0.1:{holder['port']}"
    finally:
        server = holder["server"]
        loop.call_soon_threadsafe(server.close)  # type: ignore[attr-defined]
        loop.call_soon_threadsafe(loop.stop)
        thread.join(5)
        loop.close()


def sync_sequential(urls: list[str]) -> float:
    start = time.perf_counter()
    with httpx.Client(trust_env=False) as client:
        for url in urls:
            client.get(url).raise_for_status()
    return time.perf_counter() - start


def sync_threads(urls: list[str], workers: int) -> float:
    start = time.perf_counter()
    limits = httpx.Limits(max_connections=workers, max_keepalive_connections=workers)
    with httpx.Client(trust_env=False, limits=limits) as client:  # httpx.Client is thread-safe
        with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
            for response in pool.map(client.get, urls):
                response.raise_for_status()
    return time.perf_counter() - start


async def async_gather(urls: list[str]) -> float:
    start = time.perf_counter()
    async with httpx.AsyncClient(trust_env=False) as client:  # default: 100 connections max
        responses = await asyncio.gather(*(client.get(u) for u in urls))
    for r in responses:
        r.raise_for_status()
    return time.perf_counter() - start


async def async_bounded(urls: list[str], limit: int) -> float:
    """At most `limit` requests in flight: protects the upstream and our own pool."""
    sem = asyncio.Semaphore(limit)
    start = time.perf_counter()
    async with httpx.AsyncClient(trust_env=False) as client:

        async def one(url: str) -> None:
            async with sem:
                (await client.get(url)).raise_for_status()

        await asyncio.gather(*(one(u) for u in urls))
    return time.perf_counter() - start


async def async_with_sync_client(urls: list[str]) -> float:
    """BAD: a sync client inside coroutines. gather() cannot overlap blocking calls."""
    start = time.perf_counter()
    with httpx.Client(trust_env=False) as client:

        async def one(url: str) -> None:
            client.get(url).raise_for_status()  # blocks the loop thread

        await asyncio.gather(*(one(u) for u in urls))
    return time.perf_counter() - start


def measure(n: int = 20, delay_ms: int = 100, limit: int = 5) -> dict[str, float]:
    with serve_in_thread() as base:
        urls = [f"{base}/delay/{delay_ms}" for _ in range(n)]
        runs: dict[str, Callable[[], float]] = {
            "sync sequential (httpx.Client)": lambda: sync_sequential(urls),
            f"sync + ThreadPoolExecutor({n})": lambda: sync_threads(urls, n),
            "async gather (httpx.AsyncClient)": lambda: asyncio.run(async_gather(urls)),
            f"async gather + Semaphore({limit})": lambda: asyncio.run(async_bounded(urls, limit)),
            "sync client inside async def": lambda: asyncio.run(async_with_sync_client(urls)),
        }
        return {name: round(fn(), 3) for name, fn in runs.items()}


if __name__ == "__main__":
    n, delay = 20, 100
    print(f"{n} GET requests, each answered after {delay} ms by a local asyncio server")
    for name, seconds in measure(n, delay).items():
        print(f"{name:<36} {seconds:6.3f} s")
py
from __future__ import annotations

import asyncio

import pytest

from app import fanout

N, DELAY = 20, 100


@pytest.fixture
def urls(upstream: str) -> list[str]:
    return [f"{upstream}/delay/{DELAY}" for _ in range(N)]


def test_sync_vs_async_fanout(urls: list[str]) -> None:
    seq = fanout.sync_sequential(urls)
    threads = fanout.sync_threads(urls, N)
    gathered = asyncio.run(fanout.async_gather(urls))
    bounded = asyncio.run(fanout.async_bounded(urls, 5))
    wrong = asyncio.run(fanout.async_with_sync_client(urls))
    print(
        f"\n{N} x {DELAY} ms: sequential {seq:.3f}s | threads {threads:.3f}s | gather {gathered:.3f}s"
        f" | Semaphore(5) {bounded:.3f}s | sync client in async def {wrong:.3f}s"
    )
    assert seq >= N * DELAY / 1000  # one after another
    assert gathered < seq / 5  # all 20 waits overlap
    assert threads < seq / 5
    assert bounded >= 4 * DELAY / 1000  # 20 / 5 = 4 waves
    assert wrong >= N * DELAY / 1000 * 0.9  # gather() cannot overlap blocking calls

فایل پروژه نسخه‌های Stack را ثابت می‌کند؛ asyncio_mode = "strict" اجازه می‌دهد pytest-asyncio و افزونهٔ AnyIO مجموعهٔ تست مشترک داشته باشند:

toml
[project]
name = "async-python-asyncio"
version = "0.1.0"
description = "Snippets for the Async Python chapter: event loop, coroutines, tasks, cancellation, timeouts, queues, thread pools, contextvars, a fan-out measurement"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine. TaskGroup and asyncio.timeout() (3.11+) are used only
# behind a version check, and their tests are skipped on 3.9.
requires-python = ">=3.9"
dependencies = [
    "fastapi==0.128.8",
    "starlette==0.49.3",
    "pydantic==2.13.5",
    "anyio==4.12.1",
    "httpx==0.28.1",
    # The standard extra pulls uvloop and httptools where wheels exist (not on Windows).
    "uvicorn[standard]==0.39.0",
    # Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
    "eval-type-backport==0.4.0; python_version < '3.10'",
]

[project.optional-dependencies]
test = [
    "pytest==8.4.2",
    # 1.2.0 is the last release that admits 3.9 (1.3.0 needs >=3.10).
    "pytest-asyncio==1.2.0",
]

[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[tool.setuptools]
packages = ["app"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
pythonpath = ["."]
# Strict mode: only tests marked @pytest.mark.asyncio run under pytest-asyncio, so the AnyIO
# plugin's @pytest.mark.anyio tests can live in the same suite (auto mode in both would conflict).
asyncio_mode = "strict"
asyncio_default_fixture_loop_scope = "function"
py
from __future__ import annotations

import sys
from typing import Iterator

import pytest

from app.fanout import serve_in_thread

needs_311 = pytest.mark.skipif(sys.version_info < (3, 11), reason="asyncio.TaskGroup / asyncio.timeout() are 3.11+")


@pytest.fixture(scope="session")
def upstream() -> Iterator[str]:
    """The local slow-upstream server (ephemeral port), shared by the whole session."""
    with serve_in_thread() as base:
        yield base

نگاه Python (The Python angle) ​

asyncio کتابخانه است، نه ویژگی Runtime. مفسر فقط اشیای Coroutine و نحو async def، await، async for و async with را طبق PEPهای ۴۹۲، ۵۲۵ و ۵۳۰ می‌دهد. حلقه، Task، Future، Timer، Transport و پل Thread pool کد Python در Lib/asyncio/ هستند، با شتاب‌دهندهٔ C برای Task و Future. پس uvloop می‌تواند حلقه و Trio کل چارچوب را جایگزین کند و AnyIO روی هر ۲ یک API بدهد. ۲ جزء استاندارد دیگر به همان اندازه مهم‌اند: concurrent.futures برای Poolهای پشت run_in_executor و to_thread و contextvars برای وضعیت هر Task. سومی GIL است؛ در ساخت پیش‌فرض، Thread را برای CPU خالص بی‌فایده می‌کند و ساخت Free-threaded در 3.13 آزمایشی و در 3.14 پشتیبانی‌شده آن را حذف می‌کند. تفاوت نسخه‌ها روی کد اثر دارد: 3.9 دارای to_thread است اما TaskGroup، timeout()، except* و ExceptionGroup ندارد؛ AnyIO آنجا به Backport بستهٔ exceptiongroup وابسته است. نسخهٔ 3.10 پارامتر loop= را از APIهای سطح بالا حذف کرد. نسخهٔ 3.11، asyncio.TimeoutError را نام مستعار TimeoutError داخلی کرد؛ در 3.9 ۲ کلاس متفاوت‌اند و خروجی واقعی asyncio.TimeoutError is TimeoutError: False است. از 3.11 دادن Coroutine خام به wait() ممنوع است؛ 3.9 آن را با این هشدار می‌پذیرد: DeprecationWarning: The explicit passing of coroutine objects to asyncio.wait() is deprecated since Python 3.8, and scheduled for removal in Python 3.11.

فهرست مفاهیم (The concept catalogue) ​

One turn of the event loop (one thread, BaseEventLoop._run_once)1. Timers (heap)call_later / asyncio.sleeptimeout = nearest deadline(0 if callbacks are ready)2. wait for I/O (timeout)Selector loop: readiness,epoll / kqueue / selectProactor (Windows): IOCP completions3. Ready queueready / completed I/O callbacks+ expired timers+ call_soon callbacks4. Run every ready callback, one at a time, on the loop threadTask A resumesruns to next await~50 µsTask B resumesawaits a socket read~30 µsTask C: time.sleep(0.2)never yields: 200 msdebug: "took 0.213 seconds"Task D waitsbehind C evenif its data is readyAt an await that suspends, the task registers interest (socket, timer, Future)and gives the thread back; then the loop goes round to step 1 again

هم‌روندی و اجرای موازی (Concurrency vs parallelism) حیاتی ​

به زبان ساده: هم‌روندی (Concurrency) یعنی چند کار در جریان‌اند و قدم‌هایشان در هم می‌رود؛ اجرای موازی (Parallelism) یعنی چند کار در یک لحظه روی هسته‌های مختلف اجرا می‌شوند. ۱ پیشخدمت برای ۵۰ میز هم‌روند است؛ ۱۰ پیشخدمت موازی‌اند.

بدفهمی رایج: «asyncio اجرای موازی می‌دهد.» هر حلقهٔ رویداد (Event loop) ۱ ریسمان (Thread) دارد و در هر لحظه دقیقاً یک کوروتین (Coroutine) اجرا می‌شود. asyncio انتظارها را هم‌روند می‌کند. CPU موازی در CPython به پردازه (Process)، ساخت Free-threaded یا کد C آزادکنندهٔ GIL نیاز دارد.

تعریف: در Concurrency ساختار برنامه به چند Task اجازه می‌دهد در بازه‌های زمانی هم‌پوشان پیش بروند؛ در Parallelism سخت‌افزار چند کار را هم‌زمان اجرا می‌کند. asyncio هم‌روندی مشارکتی روی ۱ Thread است؛ threading هم‌روندی پیش‌دستانه دارد و فقط هنگام آزادبودن GIL موازی می‌شود؛ multiprocessing و ProcessPoolExecutor بین Processها Parallelism می‌دهند.

     one event loop (concurrency)               4 processes (parallelism)
1    t=0     A: send request, await             core1: A computes ...
2    t=1us   B: send request, await             core2: B computes ...
3    t=2us   C: send request, await             core3: C computes ...
4    t=100ms A resumes: parse reply             core4: D computes ...
5    t=101ms B resumes: parse reply             all four finish at about the same time
6    -> 3 waits overlap; 1 core used            -> 4 computations overlap; 4 cores used

سناریوی واقعی: دروازهٔ API در هر درخواست ۵ سرویس را فراخوانی می‌کند و تأخیر کل نزدیک کندترین فراخوانی است، نه جمع همه. گزارش شبانه برای ۲٬۰۰۰٬۰۰۰ ردیف سفارش قیمت حساب می‌کند و به Process نیاز دارد. خزنده ۱۰٬۰۰۰ URL را با سقف Concurrency می‌خواند. سرویس تصویر بندانگشتی می‌تواند از کد C موازی در Thread استفاده کند؛ Pillow در بخش بزرگی از کار GIL را آزاد می‌کند، اما باید هر عملیات را جدا بررسی کرد.

مدلAPI در Pythonزمان جابه‌جاییCPU موازی؟حافظهٔ هر کارکاربرد معمول
Task مشارکتی (Cooperative)asyncio، AnyIO، Trioدر awaitنهچند KB؛ Frame و Taskانتظارهای فراوان شبکه
Thread پیش‌دستانه (Preemptive)threading، ThreadPoolExecutorمرز Bytecode یا I/Oفقط با آزادشدن GIL یا Free-threadedپشتهٔ Threadکتابخانه‌های Blocking
پردازه (Process)multiprocessing، ProcessPoolExecutorزمان‌بند سیستم‌عاملبلهیک مفسر کاملکار CPU-bound
Thread بدون GIL (Free-threaded)python3.13t / 3.14tزمان‌بند سیستم‌عاملبلهپشتهٔ ThreadCPU در Thread، اگر افزونه‌ها پشتیبانی کنند
گوروتین Go (Goroutine)Runtimeنقاط Blocking و Preemptionبله؛ GOMAXPROCSحدود چند KB و رشدپذیرهر دو

اصلاح / روش استفاده: اول گلوگاه (Bottleneck) را مشخص کنید: انتظار شبکه، asyncio؛ انتظار داخل کتابخانهٔ Sync، Thread؛ محاسبه، Process. جدول انتخاب همین تصمیم را باز می‌کند.

GIL و Python بدون GIL (Free-threaded Python) حیاتی ​

به زبان ساده: در ساخت پیش‌فرض CPython در هر لحظه فقط ۱ ریسمان (Thread) بایت‌کد Python را اجرا می‌کند. Thread هنگام انتظار کمک می‌کند چون قفل (Lock) در I/O آزاد می‌شود، اما ۲ Thread با حساب‌وکتاب Python خالص نوبتی اجرا می‌شوند. از 3.13 ساخت جداگانه‌ای بدون این قفل وجود دارد.

بدفهمی رایج: «GIL کدم را برای Thread امن می‌کند.» عملیات منفرد Bytecode را نسبت به ساختارهای داخلی مفسر اتمی می‌کند؛ خواندن، تغییر و نوشتن در چند عملیات مانند x = x + 1 یا بررسی سپس عمل روی Dict هنوز می‌تواند بین Threadها درهم برود. امنیت کد asyncio بین ۲ await هم به GIL متکی نیست؛ آنجا کار دیگری اجرا نمی‌شود.

تعریف: واژه‌نامهٔ Python می‌گوید: "The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time … Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor machines. However, some extension modules, either standard or third-party, are designed so as to release the GIL when doing computationally intensive tasks such as compression or hashing. Also, the GIL is always released when doing I/O." در PEP ۷۰۳ آمده: "CPython's global interpreter lock ("GIL") prevents multiple threads from executing Python code at the same time … This PEP proposes adding a build configuration (--disable-gil)". راهنمای Free threading نیز می‌گوید: "Starting with the 3.13 release, CPython has support for a build of Python called free threading where the global interpreter lock (GIL) is disabled."

     default build, 2 threads, pure-Python loop         free-threaded build (3.13t/3.14t)
1    T1 holds GIL: runs bytecode                        T1 runs on core 1
2    T2 waits for GIL                                   T2 runs on core 2 at the same time
3    switch interval (sys.getswitchinterval() = 0.005 s, real) -> T2 gets GIL      per-object locking inside the interpreter
4    T1 waits                                           ~1% (macOS aarch64) to 8% (x86-64 Linux) single-thread overhead
5    -> total time ~= sequential (measured: 0.37 s vs 0.42 s inline)

سناریوی واقعی: تیم حلقهٔ سنگین قیمت‌گذاری را به ThreadPoolExecutor می‌برد و شتابی نمی‌بیند: ۰٫۳۷ ثانیه در برابر ۰٫۴۲ ثانیه. همان ۴ کار در ProcessPoolExecutor در ۰٫۱۸ ثانیه تمام می‌شوند. سرویس هش فایل با hashlib از Thread سود می‌برد چون کد C قفل را آزاد می‌کند. تیم داده برای Pipeline چندریسمانی python3.14t را آزمایش می‌کند و می‌بیند یک افزونهٔ C هنگام import دوباره GIL را فعال می‌کند.

ساخت / نسخهGILروش بررسیوضعیت
CPython 3.12 و قدیمی‌تر، پیش‌فرضهمیشه روشننداردساخت استاندارد
CPython 3.13 پیش‌فرضروشنsys._is_gil_enabled() → Trueاستاندارد
CPython 3.13t با --disable-gilخاموش؛ PYTHON_GIL=1، -X gil=1 یا افزونهٔ ناسازگار C می‌تواند روشنش کندpython -VV شامل "free-threading build"؛ sysconfig.get_config_var("Py_GIL_DISABLED")آزمایشی؛ PEP 703
CPython 3.14tخاموشهمان"officially supported but still optional"؛ PEP 779، مرحلهٔ دوم
PyPyGIL داردنداردپیاده‌سازی جایگزین

اصلاح / روش استفاده: در ساخت پیش‌فرض برای CPU از Process استفاده کنید. برای I/O، GIL تعیین‌کننده نیست چون هنگام انتظار آزاد می‌شود؛ برای asyncio نیز چیزی عوض نمی‌کند چون ۱ Thread داریم. Free-threaded را گزینه‌ای برای آزمایش بدانید، نه پیش‌فرض. هشدار راهنما: "Some third-party packages, in particular ones with an extension module, may not be ready for use in a free-threaded build, and will re-enable the GIL". در این ساخت Threadها به‌طور پیش‌فرض Context فراخواننده را به ارث می‌برند؛ thread_inherit_context درست است و رفتار contextvars تغییر می‌کند.

کار I/O-bound و CPU-bound، فراخوانی Blocking و I/O غیرمسدودکننده حیاتی ​

به زبان ساده: کار وابسته به انتظار (I/O-bound) منتظر چیزی بیرون CPU مانند شبکه، دیسک یا پایگاه داده است؛ کار وابسته به پردازش (CPU-bound) وقتش را صرف محاسبه می‌کند. فراخوانی مسدودکننده (Blocking call) Thread را تا بازگشت نگه می‌دارد؛ I/O غیرمسدودکننده (Non-blocking I/O) عملیات را آغاز می‌کند و تا اعلام آمادگی سیستم‌عامل اجازهٔ کار دیگری می‌دهد.

بدفهمی رایج: «کتابخانهٔ سریع Blocking نیست.» مسئله نگه‌داشتن Thread است، نه سرعت. پاسخ ۲ میلی‌ثانیه‌ای sqlite3 ۲ ms حلقه را می‌بندد؛ ۵۰۰ فراخوانی در ثانیه کل ۱ ثانیهٔ حلقه را مصرف می‌کند. پوشاندن فراخوانی با async def هم چیزی عوض نمی‌کند: httpx.Client همگام داخل ۲۰ Coroutine زیر gather() همان ۲٫۰۷ ثانیهٔ حلقهٔ معمولی را گرفت.

تعریف: هر فراخوانی که تا پایان کار کنترل را به حلقهٔ رویداد (Event loop) پس ندهد Blocking است: time.sleep، requests.*، httpx.Client.*، urllib، socket.recv روی سوکت Blocking، psycopg2/pymysql/sqlite3، open().read() روی ذخیره‌ساز کند، subprocess.run یا حلقهٔ طولانی CPU. Non-blocking I/O سوکت را غیرمسدودکننده می‌کند و انتظار آمادگی را در Selector ثبت می‌کند. Transport و Stream در asyncio، httpx.AsyncClient، asyncpg، redis.asyncio و asyncio.create_subprocess_exec همین‌طور ساخته شده‌اند. مستندات: "Directly calling blocking_io() in any coroutine would block the event loop for its duration".

     heartbeat every 10 ms + one 200 ms job (real run, tests/test_offload.py)
1    job = time.sleep(0.2) inside async def      worst heartbeat gap 0.211 s  (loop frozen)
2    job = await asyncio.to_thread(time.sleep, 0.2)   worst gap 0.011 s  (loop free)
3    job = await asyncio.sleep(0.2)              worst gap 0.013 s  (loop free)

سناریوی واقعی: Route با async def در FastAPI، requests.post را برای پرداخت صدا می‌زند و هنگام اختلال، تأخیر صدک ۹۹ همهٔ Routeها بالا می‌رود. Worker شبیه Celery برای Backoff داخل Coroutine از time.sleep استفاده می‌کند. توسعه‌دهندهٔ Django به FastAPI می‌آید ولی psycopg2 را در async def نگه می‌دارد. ارسال‌کنندهٔ Log با open() داخل Coroutine از فایل‌سیستم شبکه‌ای می‌خواند.

فراخوانیحلقه را می‌بندد؟جایگزین Asyncیا برون‌سپاری با
time.sleep(s)بلهawait asyncio.sleep(s)ندارد
requests.get، httpx.Client.get، urllib.requestبلهawait httpx.AsyncClient().get / aiohttpto_thread
psycopg2، pymysql، sqlite3بلهasyncpg، psycopg 3 async، aiomysql، aiosqlite، AsyncSession در SQLAlchemyto_thread / Route با def
redis.Redisبلهredis.asyncio.Redisto_thread
open().read()، pathlib.read_textبله؛ معمولاً کوتاهanyio.Path / anyio.open_file؛ AnyIO: "Operations that perform disk I/O (like read_bytes()) are run in a worker thread"to_thread
subprocess.runبلهasyncio.create_subprocess_execto_thread
boto3بلهaiobotocore؛ طبق README، Client ناهمگام AWS بر پایهٔ botocore و aiohttp/asyncio؛ یا aioboto3to_thread
json.loads روی 50 MB و Pydantic روی بدنهٔ عظیمبله؛ CPUندارددر صورت اهمیت، ProcessPoolExecutor

اصلاح / روش استفاده: در async def هر فراخوانی باید کتابخانهٔ Async را await کند یا به Thread سپرده شود. تست ضربان (Heartbeat) در اجرای کد Blocking راه ارزانی برای اثبات آزادماندن حلقه است؛ Debug mode نیز Callbackهای بیش از ۱۰۰ ms را ثبت می‌کند.

حلقهٔ رویداد (Event loop): Selector، Callback و uvloop حیاتی ​

به زبان ساده: حلقهٔ رویداد (Event loop) یک while True با ۳ مجموعه است: زمان‌سنج‌ها (Timers)، تابع‌های بازخوان آماده (Ready callbacks) و سوکت‌های ثبت‌شده. در هر دور از سیستم‌عامل می‌پرسد کدام سوکت آماده است، حداکثر تا نزدیک‌ترین Timer منتظر می‌ماند، Callbackهای مربوط را صف می‌کند و یکی‌یکی اجرا می‌کند.

بدفهمی رایج: «حلقه Taskها را در پس‌زمینه و موازی اجرا می‌کند.» خود حلقه همان Thread اجرای Taskهاست. تا یک Callback اجرا می‌شود، حلقه سراغ سوکت و Timer نمی‌رود؛ معنای مسدودکردن حلقه همین است.

تعریف: مستندات می‌گویند: "Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses." در CPython، BaseEventLoop._run_once مهلت select را از نزدیک‌ترین Handle زمان‌بندی‌شده حساب می‌کند، self._selector.select(timeout) را صدا می‌زند، Callbackهای I/O و Timer منقضی را به _ready می‌افزاید و Handleهای _ready را اجرا می‌کند. در Proactor همین فراخوانی روی پورت تکمیل IOCP منتظر عملیات تمام‌شده می‌ماند، نه سوکت آماده. Debug mode اگر مدت از slow_callback_duration، پیش‌فرض ۰٫۱ ثانیه، بیشتر باشد 'Executing %s took %.3f seconds' را ثبت می‌کند. ماژول selectors با DefaultSelector بهترین سازوکار سیستم‌عامل را انتخاب می‌کند: epoll در Linux و kqueue در macOS/BSD. در Windows از 3.8، ProactorEventLoop مبتنی بر IOCP پیش‌فرض است. uvloop کل حلقه را با libuv، کتابخانهٔ رویداد Node.js، جایگزین می‌کند.

     one loop iteration (_run_once), simplified
1    timeout = 0 if ready callbacks exist else (nearest timer - now)
2    events = selector.select(timeout)             <- the only place the loop sleeps (epoll/kqueue; IOCP on Windows proactor)
3    for each ready socket: append its reader/writer callback to _ready
4    for each expired timer: append its callback to _ready
5    for each handle in _ready (FIFO): handle._run()   <- your coroutine resumes here
6         ... runs until its next await, which registers a socket/timer/Future and returns
7    go to 1

سناریوی واقعی: Uvicorn برای هر Process Worker یک حلقه دارد و همهٔ درخواست‌های آن Worker را روی همان اجرا می‌کند. سرور تست این فصل حلقهٔ مستقل در Thread پس‌زمینه با loop.run_forever() دارد. GUI یا Jupyter از قبل حلقه دارد و به همین دلیل asyncio.run() آنجا خطا می‌دهد. Uvicorn در صورت نصب uvloop خودکار آن را انتخاب می‌کند؛ خروجی واقعی: --loop auto: uvloop.Loop.

حلقهسکوBackendروش استفادهنکته
SelectorEventLoopپیش‌فرض Unix؛ اختیاری Windowsselectors.DefaultSelector؛ epoll / kqueue / poll / selectasyncio.runواقعی در macOS: _UnixSelectorEventLoop
ProactorEventLoopپیش‌فرض Windows از 3.8IOCPasyncio.run در Windowsپشتیبانی زیرپردازه و Pipe
uvloop LoopLinux و macOS؛ بدون Windowslibuv، Cythonuvloop.run(main())؛ جایگزین README برای 3.11 و قبل: asyncio.Runner(loop_factory=uvloop.new_event_loop) یا uvloop.install()README: "uvloop makes asyncio 2-4x faster"
Uvicorn --loop autoهمهuvloop اگر import شود، وگرنه asynciouvicorn[standard]، uvloop را نصب می‌کندمستندات Uvicorn: "not compatible with Windows or PyPy"
Trio / Backend trio در AnyIOهمهحلقهٔ خود Trioanyio.run(main, backend="trio")مدل لغو متفاوت

اصلاح / روش استفاده: کد Blocking را روی Thread حلقه اجرا نکنید. داخل Coroutine از asyncio.get_running_loop() استفاده کنید؛ مستندات آن را بر get_event_loop() با رفتار متغیر بین نسخه‌ها ترجیح می‌دهند. برای uvloop در Linux و macOS، uvicorn[standard] نصب کنید. تست tests/test_uvloop.py اجرای همان Coroutineها بدون تغییر روی uvloop را نشان می‌دهد.

py
from __future__ import annotations

import asyncio
import sys

import pytest

from app import basics

uvloop = pytest.importorskip("uvloop")  # no wheels on Windows


def test_same_code_runs_on_uvloop() -> None:
    async def main() -> tuple[str, list[str]]:
        loop_type = type(asyncio.get_running_loop()).__module__
        results, _ = await basics.concurrent([0.01, 0.01])
        return loop_type, results

    if sys.version_info >= (3, 11):
        loop_type, results = uvloop.run(main())
    else:  # 3.9/3.10: the policy API (deprecated in 3.14 and scheduled for removal in 3.16)
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
        try:
            loop_type, results = asyncio.run(main())
        finally:
            asyncio.set_event_loop_policy(None)
    assert loop_type.startswith("uvloop")
    assert results == ["job0", "job1"]

کوروتین (Coroutine)، async def، await، Awaitable و Future حیاتی ​

به زبان ساده: async def تابعی تعریف می‌کند که می‌تواند مکث کند. فراخوانی آن شیء کوروتین (Coroutine) می‌دهد. await آن را اجرا می‌کند تا تمام شود یا به انتظار چیزی برسد که هنوز آماده نیست؛ آن وقت کل زنجیرهٔ Coroutineهای منتظر متوقف می‌شود و حلقه کار دیگری اجرا می‌کند.

بدفهمی رایج: «await کاری را در پس‌زمینه شروع می‌کند.» await coro() همین حالا و داخل Task جاری coro را اجرا می‌کند و فراخواننده منتظرش می‌ماند. اجرای هم‌زمان ۲ کار به ۲ Task با create_task، gather یا TaskGroup نیاز دارد. ۳ await پشت‌سرهم جمع زمان‌هایشان را می‌گیرند: در اجرای واقعی sequential() با ۳ انتظار ۵۰ میلی‌ثانیه‌ای حداقل ۰٫۱۵ ثانیه و concurrent() کمتر از ۰٫۱۲ ثانیه شد.

تعریف: PEP ۴۹۲ با async def، Coroutine را "a proper standalone concept in Python" کرد؛ تابع دارای await نمی‌تواند def معمولی باشد. شیء قابل انتظار (Awaitable) می‌تواند Coroutine، Future، Task یا هر شیء با __await__ برگردانندهٔ Iterator باشد. asyncio.Future یک Future سطح پایین با result()، exception()، done()، cancelled() و add_done_callback() است. await آن تا فراخوانی set_result یا set_exception معلق می‌ماند. Task زیرکلاس Future است و Coroutine را پیش می‌برد. عبارت await فقط داخل async def یا در سطح بالای python -m asyncio معتبر است.

     await chain inside one Task
1    Task.__step: coro.send(None)        -> handler() runs
2    handler: await service()            -> service() runs inline (no new task)
3    service: await client.get(url)      -> ... down to a socket read
4    socket not ready: a Future is yielded up the chain to the Task
5    Task registers a wake-up callback on that Future, returns to the loop
6    loop runs other tasks; later the selector reports the socket ready
7    Future.set_result(data) -> callback schedules Task.__step again
8    Task: coro.send(None) resumes the innermost await; values flow back up

سناریوی واقعی: متد سرویس فقط چون یک Client ناهمگام را صدا می‌زند async def است؛ این درست است. تابع کمکی async def که هرگز await ندارد همچنان شیء Coroutine می‌سازد و همهٔ فراخواننده‌ها را Async می‌کند. API مبتنی بر Callback، مثلاً مصرف‌کنندهٔ پیام، با loop.create_future() به Awaitable تبدیل می‌شود. تستی که تابع Async را بدون await صدا می‌زند سبز می‌شود چون هیچ‌چیز اجرا نشده.

نوعساخته‌شده باچه وقت اجرا می‌شوددوبار await؟لغو
Coroutineفراخوانی async defهنگام await یا قرارگرفتن در Taskنه؛ RuntimeError: cannot reuse already awaited coroutineclose()
Taskcreate_task، ensure_future، gather، TaskGroup.create_taskفوری زمان‌بندی؛ شروع در await بعدی سازندهبله؛ همان نتیجهtask.cancel()
Futureloop.create_future()، run_in_executorوقتی کسی نتیجه را تعیین کندبلهfut.cancel()
concurrent.futures.FuturePoolهای Thread/Processداخل Workerنه؛ تبدیل با asyncio.wrap_futurecancel() پیش از شروع
مولد ناهمگام (Async generator)async def با yieldهر قدم async forکاربرد نداردaclose()

اصلاح / روش استفاده:

py
"""Coroutines, awaitables and the event loop: what `async def` and `await` really do."""
from __future__ import annotations

import asyncio
import time


async def fetch(name: str, delay: float) -> str:
    # A coroutine function: calling it returns a coroutine object, nothing runs yet.
    await asyncio.sleep(delay)  # yields to the event loop until the timer fires
    return name


async def sequential(delays: list[float]) -> tuple[list[str], float]:
    """Awaiting one coroutine after another: total time is the SUM of the delays."""
    start = time.perf_counter()
    results = [await fetch(f"job{i}", d) for i, d in enumerate(delays)]
    return results, time.perf_counter() - start


async def concurrent(delays: list[float]) -> tuple[list[str], float]:
    """gather() wraps each coroutine in a Task: total time is the MAX of the delays."""
    start = time.perf_counter()
    results = await asyncio.gather(*(fetch(f"job{i}", d) for i, d in enumerate(delays)))
    return list(results), time.perf_counter() - start


def interleaving_trace() -> list[str]:
    """Shows the loop switching between two tasks only at `await` points."""
    trace: list[str] = []

    async def worker(name: str) -> None:
        for step in range(2):
            trace.append(f"{name} step {step}")
            await asyncio.sleep(0)  # a bare yield point: let other ready tasks run

    async def main() -> None:
        await asyncio.gather(worker("A"), worker("B"))

    asyncio.run(main())
    return trace


def await_without_suspension() -> list[str]:
    """`await` yields to the loop only if the awaitable actually suspends.

    Awaiting a coroutine that returns at once, or a Future that is already done, continues
    without a task switch; `await asyncio.sleep(0)` is the explicit "let others run" point.
    """
    order: list[str] = []

    async def instant() -> int:
        return 1

    async def main() -> None:
        async def child() -> None:
            order.append("child")

        task = asyncio.create_task(child())
        await instant()
        order.append("after await instant()")
        done = asyncio.get_running_loop().create_future()
        done.set_result(None)
        await done
        order.append("after await done Future")
        await asyncio.sleep(0)
        order.append("after await asyncio.sleep(0)")
        await task

    asyncio.run(main())
    return order


def awaitable_kinds() -> dict[str, bool]:
    """Coroutines, Tasks and Futures are all awaitables; a plain function result is not."""

    async def main() -> dict[str, bool]:
        coro = fetch("x", 0)
        task = asyncio.ensure_future(fetch("y", 0))  # same as create_task for a coroutine
        fut = asyncio.get_running_loop().create_future()
        fut.set_result("z")
        kinds = {
            "coroutine": asyncio.iscoroutine(coro),
            "task_is_future": isinstance(task, asyncio.Future),
            "future_awaitable": hasattr(fut, "__await__"),
        }
        await asyncio.gather(coro, task, fut)
        return kinds

    return asyncio.run(main())
py
from __future__ import annotations

import asyncio

import pytest

from app import basics


@pytest.mark.asyncio
async def test_sequential_awaits_add_up() -> None:
    results, elapsed = await basics.sequential([0.05, 0.05, 0.05])
    assert results == ["job0", "job1", "job2"]
    assert elapsed >= 0.15


@pytest.mark.asyncio
async def test_gather_overlaps_the_waits() -> None:
    results, elapsed = await basics.concurrent([0.05, 0.05, 0.05])
    assert results == ["job0", "job1", "job2"]  # input order, not completion order
    assert elapsed < 0.12


def test_tasks_switch_only_at_await_points() -> None:
    assert basics.interleaving_trace() == ["A step 0", "B step 0", "A step 1", "B step 1"]


def test_await_does_not_yield_unless_it_suspends() -> None:
    assert basics.await_without_suspension() == [
        "after await instant()",
        "after await done Future",
        "child",
        "after await asyncio.sleep(0)",
    ]


def test_awaitable_kinds() -> None:
    assert basics.awaitable_kinds() == {"coroutine": True, "task_is_future": True, "future_awaitable": True}


def test_calling_a_coroutine_function_runs_nothing() -> None:
    coro = basics.fetch("x", 0)
    assert asyncio.iscoroutine(coro)
    assert asyncio.run(coro) == "x"  # only the event loop runs it


@pytest.mark.asyncio
async def test_asyncio_run_inside_a_running_loop_fails() -> None:
    coro = basics.fetch("x", 0)
    with pytest.raises(RuntimeError, match="cannot be called from a running event loop"):
        asyncio.run(coro)
    coro.close()  # avoid "coroutine was never awaited"

وظیفه‌ها (Tasks): create_task، زمان‌بندی، رهاکردن و ارجاع حیاتی ​

به زبان ساده: وظیفه (Task) واحد هم‌روندی asyncio است: «این Coroutine را کنار من اجرا کن». asyncio.create_task(coro) آن را زمان‌بندی می‌کند و فوری برمی‌گردد؛ Task جدید وقتی Task فعلی await کند شروع می‌شود.

بدفهمی رایج: «نتیجه را نمی‌خواهم، پس Task را دور می‌اندازم.» مستندات صریح‌اند: "Save a reference to the result of this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn't referenced elsewhere may get garbage collected at any time, even before it's done. For reliable "fire-and-forget" background tasks, gather them in a collection". استثنای Task رهاشده هم گم می‌شود؛ در بهترین وضعیت هنگام جمع‌آوری حافظه Task exception was never retrieved می‌بینید. هنگام خاموشی هم کسی آن را لغو نمی‌کند و Task was destroyed but it is pending! می‌گیرید.

تعریف: asyncio.create_task(coro, *, name=None, context=None)، Coroutine را در Task می‌گذارد، اولین قدم را با loop.call_soon زمان‌بندی می‌کند و Task را برمی‌گرداند. context در 3.11 اضافه شد؛ نسخه‌های جاری eager_start را نیز می‌پذیرند. Task در کپی Context جاری contextvars اجرا می‌شود. از 3.12 می‌توان asyncio.eager_task_factory را تنظیم کرد تا Coroutine هنگام create_task به‌صورت همگام تا اولین تعلیق واقعی اجرا شود: "Tasks are only scheduled on the event loop if they block".

     caller task                                   new task (real order, test_tasks.py)
1    t = create_task(child())                       scheduled, not started
2    order.append("after create_task")
3    await asyncio.sleep(0)   -- yields --------->  child runs: order.append("child runs")
4    order.append("after first await")   <-------  child done
5    await t                                        result (or exception) delivered here
     -> ["after create_task", "child runs", "after first await"]

سناریوی واقعی: Endpoint پس‌زمینه Webhook می‌فرستد و 202 برمی‌گرداند؛ Handler وب‌سوکت Task خواندن و نوشتن می‌سازد؛ Lifespan کار دوره‌ای تازه‌کردن Cache آغاز می‌کند؛ ثبت ممیزی نباید پاسخ را عقب بیندازد. هرکدام مالک می‌خواهند که ارجاع نگه دارد، شکست را Log کند و هنگام خاموشی لغو کند.

الگوارجاع نگه می‌داردخطا دیده می‌شودلغو در خاموشینتیجه
asyncio.create_task(x()) و رهاکردننهنهنهباگ
tasks.add(t); t.add_done_callback(tasks.discard)؛ الگوی مستنداتبلهفقط اگر بخوانیداگر Set را لغو کنیدحداقل لازم
کلاس BackgroundTasks در قطعه‌کد؛ Set، Callback ثبت شکست با Traceback و drain(timeout)بلهبله؛ Log مالک و شمارش در /healthبله، پس از مهلتپیش‌فرض خوب؛ خواندن استثنا گزارش asyncio را خاموش می‌کند، پس مالک باید Log کند
async with TaskGroup() / Task group در AnyIOبلهبله؛ ExceptionGroupخروج عادی منتظر همه می‌ماند؛ لغو فقط با شکست فرزند یا بدنه یا tg.cancel() در 3.15+ / tg.cancel_scope.cancel()مناسب عمر یک بلوک؛ Worker بی‌پایان باید صریح لغو شود
BackgroundTasks در FastAPIبله؛ پس از پاسخ همان درخواستLog می‌شودتا پایان اجرا می‌شودکار کوچک پس از پاسخ؛ فصل مربوط
صف کار؛ Celery، arq، RQ، Dramatiqپایداربله، با Retryاز Restart جان سالم می‌بردکاری که نباید گم شود

اصلاح / روش استفاده: نتیجهٔ هر create_task را ذخیره کنید. اگر مالک در Callback پایان، task.exception() را بخواند، asyncio دیگر Task exception was never retrieved چاپ نمی‌کند؛ پس Callback باید خودش شکست را Log کند، مانند log.error(..., exc_info=exc) در قطعه‌کد، و آن را قابل مشاهده کند؛ /health در برنامهٔ بعد background_errors می‌دهد. Taskهای پس‌زمینهٔ سرویس را در یک شیء ساخته‌شده در Lifespan نگه دارید؛ BackgroundTasks در app/after.py همین کار را می‌کند. هنگام خاموشی آن را تخلیه کنید و کار لازم پس از Crash را به صف واقعی ببرید.

gather و return_exceptions حیاتی ​

به زبان ساده: await asyncio.gather(a(), b(), c()) ۳ کار را هم‌روند اجرا می‌کند و نتیجه‌ها را به ترتیب ورودی در فهرست می‌دهد.

بدفهمی رایج: «شکست یکی بقیه را لغو می‌کند.» چنین نیست. مستندات: "If return_exceptions is False (default), the first raised exception is immediately propagated to the task that awaits on gather(). Other awaitables in the aws sequence won't be cancelled and will continue to run." قطعه‌کد نشان می‌دهد پس از شکست a، کار b تمام شد: finished == ["b"]. با return_exceptions=True: "exceptions are treated the same as successful results, and aggregated in the result list".

تعریف: asyncio.gather(*aws, return_exceptions=False)، Coroutineها را به Task تبدیل می‌کند و فهرست نتیجه را به ترتیب ورودی می‌دهد. "If gather() is cancelled, all submitted awaitables (that have not completed yet) are also cancelled". اما پس از انتقال استثنا، gather.cancel() دیگر "won't cancel any other awaitables". سقف هم‌روندی ندارد: gather(*(fetch(u) for u in urls)) برای ۱۰٬۰۰۰ URL، ۱۰٬۰۰۰ Task را یک‌جا آغاز می‌کند.

     gather(a: fails at 10 ms, b: 50 ms), return_exceptions=False (real, test_tasks.py)
1    t=0     both tasks start
2    t=10ms  a raises ValueError -> gather raises it in the caller
3    t=10ms  caller handles the error and moves on ...
4    t=50ms  b still completes; its result is discarded unless someone awaits it
     same with return_exceptions=True -> ["a", ValueError("b failed"), "c"] in input order

سناریوی واقعی: صفحهٔ محصول قیمت، موجودی و نظر را می‌گیرد؛ بررسی سلامت ۳ وابستگی را با return_exceptions=True جدا گزارش می‌کند؛ ورود گروهی داده ۵۰ ردیف در هر نوبت می‌فرستد، با gather در حلقهٔ تکه‌ها یا Semaphore؛ تجمیع داده نباید با شکست یک منبع کل صفحه را خراب کند.

نیازابزاردلیل
همهٔ نتیجه‌ها و شکست سریع؛ ادامهٔ هم‌گروهی‌ها مجاز استgather()ساده؛ بدانید دیگران لغو نمی‌شوند
همهٔ نتیجه‌ها با پذیرش شکست جزئیgather(..., return_exceptions=True)هر عضو را با isinstance(r, Exception) بررسی کنید
شکست سریع همراه لغو هم‌گروهی‌هاTaskGroup از 3.11+ یا Task group در AnyIOهم‌روندی ساخت‌یافته (Structured concurrency)
نتیجه به‌محض آماده‌شدنas_completedارسال تدریجی نتیجهٔ جزئی
سقف هم‌روندیSemaphore دور هر فراخوانی یا Queue Workerهامحافظت از بالادست و Pool
پخش بسیار بزرگ کار (Fan-out)Worker pool روی Queueتعداد Task ثابت

اصلاح / روش استفاده: tasks.gather_fail_fast، gather_collect و bounded_gather در app/tasks.py هستند؛ در بعد وارد شده‌اند و در tests/test_tasks.py تست می‌شوند. bounded_gather همان Fan-out با Semaphore در اندازه‌گیری است.

py
from __future__ import annotations

import asyncio

import pytest

from app import tasks
from tests.conftest import needs_311


@pytest.mark.asyncio
async def test_create_task_runs_at_next_await() -> None:
    assert await tasks.create_task_starts_immediately() == ["after create_task", "child runs", "after first await"]


@pytest.mark.asyncio
async def test_gather_propagates_first_error_and_does_not_cancel_others() -> None:
    outcome, finished = await tasks.gather_fail_fast()
    assert outcome == "a failed"
    assert finished == ["b"]  # b kept running after a failed


@pytest.mark.asyncio
async def test_gather_return_exceptions_keeps_order() -> None:
    results = await tasks.gather_collect()
    assert results[0] == "a" and results[2] == "c"
    assert isinstance(results[1], ValueError)


@pytest.mark.asyncio
async def test_as_completed_yields_in_completion_order() -> None:
    assert await tasks.first_finished_order() == ["fast", "mid", "slow"]


@pytest.mark.asyncio
async def test_wait_first_completed_then_cancel_losers() -> None:
    winner, cancelled = await tasks.race_first_completed()
    assert winner == "replica-b"
    assert cancelled == 1


@pytest.mark.asyncio
async def test_background_tasks_keeps_references_and_collects_errors(caplog: pytest.LogCaptureFixture) -> None:
    bg = tasks.BackgroundTasks()
    bg.spawn(tasks.step("ok", 0.01))
    bg.spawn(tasks.step("bad", 0.01, fail=True))
    assert len(bg) == 2  # strongly referenced until done
    await asyncio.sleep(0.05)
    assert len(bg) == 0
    assert [str(e) for e in bg.errors] == ["bad failed"]
    assert any("background task" in r.message and "failed" in r.message for r in caplog.records)


@pytest.mark.asyncio
async def test_drain_cancels_what_does_not_finish_in_time() -> None:
    bg = tasks.BackgroundTasks()
    bg.spawn(tasks.step("quick", 0.01))
    slow = bg.spawn(asyncio.sleep(5))
    assert await bg.drain(timeout=0.1) == 1
    assert slow.cancelled()


@pytest.mark.asyncio
async def test_bounded_gather_preserves_order() -> None:
    funcs = [lambda i=i: tasks.step(str(i), 0.01) for i in range(10)]
    assert await tasks.bounded_gather(funcs, limit=3) == [str(i) for i in range(10)]


@needs_311
@pytest.mark.asyncio
async def test_taskgroup_cancels_siblings_and_groups_errors() -> None:  # expected on 3.11+
    messages, cancelled = await tasks.taskgroup_fail_fast()
    assert messages == ["a failed"]
    assert cancelled == ["b", "c"]

TaskGroup و هم‌روندی ساخت‌یافته (Structured concurrency) مهم ​

به زبان ساده: گروه وظیفه (Task group) مالک Taskهای داخل بلوک است. در خروج عادی منتظر پایان همه می‌ماند؛ فقط اگر یکی یا بدنه خطا بدهد بقیه لغو می‌شوند و خطاها با هم بیرون می‌آیند. هیچ Taskی از کد سازنده‌اش بیشتر عمر نمی‌کند. بنابراین فرزند بی‌پایان، مثل مصرف‌کنندهٔ while True، بلوک را تا لغو باز نگه می‌دارد. AnyIO نیز می‌گوید: "If a child task, or the code in the enclosed context block raises an exception, all child tasks are cancelled. Otherwise the context manager just waits until all child tasks have exited before proceeding." برای توقف فرزند دائمی، tg.cancel() در 3.15+، لغو مستقیم Taskهای نگه‌داشته‌شده از tg.create_task با .cancel()، تنظیم Event مورد مشاهدهٔ آن‌ها، asyncio.timeout() پیرامونی یا tg.cancel_scope.cancel() در AnyIO لازم است.

بدفهمی رایج: «TaskGroup همان gather با نحو زیباتر است.» تفاوت در لغو و عمر است. gather پس از اولین خطا هم‌گروهی‌ها را رها می‌کند تا ادامه دهند؛ TaskGroup لغوشان می‌کند، منتظر پاک‌سازی می‌ماند و همهٔ خطاهای غیرلغو را با ExceptionGroup می‌دهد. Task گم نمی‌شود چون خروج از async with با فرزند زنده ممکن نیست.

تعریف؛ 3.11+، مورد انتظار و روی 3.9 اجرا نشده: "The async with statement will wait for all tasks in the group to finish … The first time any of the tasks belonging to the group fails with an exception other than asyncio.CancelledError, the remaining tasks in the group are cancelled. No further tasks can then be added to the group … Once all tasks have finished, if any tasks have failed with an exception other than asyncio.CancelledError, those exceptions are combined in an ExceptionGroup or BaseExceptionGroup … which is then raised." استثناهای KeyboardInterrupt و SystemExit خودشان دوباره پرتاب می‌شوند. نسخهٔ 3.13، "handling of simultaneous internal and external cancellations" را بهتر کرد. نسخهٔ 3.15 در ۲۰۲۶-۱۰-۰۹، tg.cancel() را برای "a non-exceptional, early exit of the task group's lifetime" افزود. یادداشت تغییرات می‌گوید: "Previously this would involve unintuitive boilerplate such as an extra task raising a custom exception which is then suppressed as it exits the task group". رسیدگی تفکیکی با except* از PEP ۶۵۴ است و پیش از 3.11 خطای نحو می‌دهد. نام قاعدهٔ «هر Task یک حوزهٔ والد دارد که منتظرش می‌ماند» هم‌روندی ساخت‌یافته (Structured concurrency) است؛ از Trio آمده و AnyIO آن را به نسخه‌های قدیمی asyncio می‌آورد.

     async with asyncio.TaskGroup() as tg:  (expected on 3.11+; same shape ran for real with AnyIO)
1    tg.create_task(slow("b"))       tg.create_task(slow("c"))       tg.create_task(fail("a"))
2    t=10ms  a raises ValueError("a failed")
3            group cancels b and c -> CancelledError inside each; their finally/except blocks run
4            the body of `async with` is cancelled too if it is still awaiting
5            __aexit__ waits until b and c have finished cancelling
6            raise ExceptionGroup(..., [ValueError("a failed")])   # every non-cancellation error
7    except* ValueError as eg: ...   # handle; other exception types keep propagating

سناریوی واقعی: Checkout باید موجودی رزرو کند، پرداخت را تأیید کند و هزینهٔ ارسال بگیرد و با شکست یکی هر ۳ را متوقف کند. جلسهٔ WebSocket خواننده و نویسنده‌ای دارد که باید با پایان یکی هر ۲ متوقف شوند. جست‌وجوی Scatter-gather باید با خرابی Shard سریع خطا بدهد. Lifespan چند حلقهٔ پس‌زمینه را در یک گروه نگه می‌دارد.

موضوعgather()gather(return_exceptions=True)TaskGroup از 3.11+create_task_group() در AnyIO
هم‌گروهی‌ها در اولین خطاادامه می‌دهندادامه می‌دهندلغو می‌شوندلغو می‌شوند
خروجیاولین استثنافهرست دارای استثناExceptionGroupExceptionGroup؛ Backport روی ≤ 3.10
فرزند بیشتر از بلوک زنده می‌ماند؟بله، اگر await نشودبلهنهنه
افزودن Task بعدینهنهبله؛ tg.create_task تا بازبودنبله؛ tg.start_soon
نسخهٔ Pythonهمههمه3.11+3.9+؛ AnyIO 4.12.1 روی 3.9
نتیجهمقدار بازگشتیمقدار بازگشتیtask.result() بعد از بلوکوضعیت مشترک یا start()

اصلاح / روش استفاده: در 3.11+ برای Fan-out با نتیجه‌های لازم کنار هم، TaskGroup را ترجیح بدهید، کل گروه را در asyncio.timeout() بگذارید و با except* رسیدگی کنید. tasks.taskgroup_fail_fast() برای 3.11 نوشته شده اما گروه را با except Exception معمولی می‌گیرد تا فایل از نظر نحو 3.9 معتبر بماند؛ تست آن در 3.9 Skipped می‌شود. پیاده‌سازی AnyIO پایین واقعاً اجرا شده است.

python
# Python 3.11+ (expected, not run here): fail fast, cancel siblings, handle by type
async def checkout(order_id: int) -> Receipt:
    async with asyncio.timeout(2.0):
        async with asyncio.TaskGroup() as tg:
            stock = tg.create_task(reserve_stock(order_id))
            payment = tg.create_task(authorise_payment(order_id))
            shipping = tg.create_task(quote_shipping(order_id))
    return Receipt(stock.result(), payment.result(), shipping.result())

try:
    receipt = await checkout(42)
except* PaymentDeclined as eg:      # one or more PaymentDeclined in the group
    log.warning("declined: %s", eg.exceptions)
except* TimeoutError:
    log.error("checkout budget exceeded")

as_completed و wait با FIRST_COMPLETED مهم ​

به زبان ساده: as_completed نتیجه‌ها را به ترتیب تکمیل می‌دهد تا روی سریع‌ترین زودتر عمل کنید. wait وقتی شرط برقرار شد، ۲ Set تمام‌شده و در حال اجرا می‌دهد: اولین پایان، اولین خطا یا پایان همه.

بدفهمی رایج: «wait(timeout=...) کار ناتمام را لغو می‌کند.» مستندات می‌گویند: "Futures or Tasks that aren't done when the timeout occurs are simply returned in the second set" و "Unlike wait_for(), wait() does not cancel the futures when a timeout occurs." برای as_completed هم "does not cancel the tasks running the supplied awaitables" صادق است. لغو بازنده‌ها مسئولیت شماست؛ فراموش‌کردنش Task و اتصال (Connection) نشت می‌دهد.

تعریف: asyncio.as_completed(aws, *, timeout=None) یک Iterator از Awaitableها می‌دهد؛ از 3.13 Iterator ناهمگام هم هست. هر عضو نتیجهٔ بعدی را می‌دهد و گذشت مهلت TimeoutError می‌سازد. asyncio.wait(aws, *, timeout=None, return_when=ALL_COMPLETED)، (done, pending) می‌دهد. شرط return_when می‌تواند FIRST_COMPLETED، یعنی "when any future finishes or is cancelled"، یا FIRST_EXCEPTION یا ALL_COMPLETED باشد. Timeout استثنا نمی‌دهد. از 3.11، wait() فقط Task/Future می‌پذیرد؛ Coroutine خام در 3.9 هشدار DeprecationWarning واقعی می‌دهد.

     race two replicas (real, tasks.race_first_completed)
1    tasks = {create_task(step("replica-a", 0.05)), create_task(step("replica-b", 0.01))}
2    done, pending = await asyncio.wait(tasks, return_when=FIRST_COMPLETED)   # at ~10 ms
3    done = {replica-b}; pending = {replica-a}
4    for t in pending: t.cancel(); await gather(*pending, return_exceptions=True)
5    -> winner "replica-b", 1 task cancelled
     as_completed([slow 50 ms, fast 10 ms, mid 30 ms]) -> "fast", "mid", "slow" (real)

سناریوی واقعی: درخواست پوششی (Hedged request) را به ۲ نمونه (Replica) می‌فرستید، اولین پاسخ را می‌گیرید و دیگری را لغو می‌کنید. صفحهٔ جست‌وجو نتیجهٔ هر تأمین‌کننده را به‌محض رسیدن نمایش می‌دهد. ناظر با FIRST_EXCEPTION منتظر خرابی اولین Worker می‌ماند و آن را دوباره اجرا می‌کند. اسکریپت استقرار تا ۳۰ ثانیه منتظر بررسی سلامت‌ها می‌ماند و ناتمام‌ها را گزارش می‌کند.

خواستهفراخوانیسپس
سریع‌ترین از N کار و لغو بقیهwait(..., return_when=FIRST_COMPLETED)pending را لغو و await کنید
هر نتیجه به‌محض رسیدنfor aw in as_completed(aws): r = await aw؛ از 3.13: async forدر خروج زودهنگام بقیه را لغو کنید
توقف در اولین خطا و مشاهدهٔ بقیهwait(..., return_when=FIRST_EXCEPTION)Task شکست‌خورده در done است
مهلت بدون لغوwait(..., timeout=t)دربارهٔ pending تصمیم بگیرید
مهلت همراه لغوwait_for / timeout()کار دیگری لازم نیست

اصلاح / روش استفاده: first_finished_order() و race_first_completed() در app/tasks.py هستند. کنار wait و as_completed همیشه لغو صریح کاری را بگذارید که دیگر لازم نیست.

From coroutine object to finished Task, and what cancel() really doescoroutine objectfetch() called,nothing runs yetcreate_taskpendingin the ready queueweak ref from looprunninguntil the next awaitthen suspended on aFuture / socket / timerawait / resumedone: result()done: exception()cancelled()task.cancel() is a request1. cancel() returns at once; nothing stops yet2. CancelledError raised at the task's next await3. finally / async with exits run (cleanup)4. error propagates: state becomes cancelled()a CPU loop without await is never interruptedexcept CancelledError: return ...swallowed: task ends "done" with a result,TaskGroup / timeout() can misbehaveawait asyncio.shield(inner)the awaiting task gets CancelledError,the inner task keeps running (keep a reference)

لغو (Cancellation): CancelledError و shield حیاتی ​

به زبان ساده: task.cancel() درخواست توقف می‌دهد. Python در await بعدی Task، استثنای CancelledError ایجاد می‌کند؛ پشته مانند هر استثنا باز می‌شود، finally و خروج از async with اجرا می‌شوند و سپس Task لغوشده علامت می‌خورد.

بدفهمی رایج: «گرفتن CancelledError رسیدگی خوب به خطاست.» گرفتن برای پاک‌سازی درست است، اما دوباره پرتاب‌نکردنش لغو (Cancellation) را خراب می‌کند. مستندات: "In case asyncio.CancelledError is explicitly caught, it should generally be propagated when clean-up is complete … The asyncio components that enable structured concurrency, like asyncio.TaskGroup and asyncio.timeout(), are implemented using cancellation internally and might misbehave if a coroutine swallows asyncio.CancelledError." در قطعه‌کد، stubborn() از except CancelledError مقدار برمی‌گرداند و Task «تمام‌شده ولی لغونشده» است؛ نتیجهٔ واقعی swallowed_cancel() is True. Task ممیزی برنامهٔ قبل همین کار را می‌کند. except Exception هم آن را نمی‌گیرد چون از 3.8، CancelledError زیر BaseException است؛ روی 3.9 نیز کلاس پایهٔ واقعی BaseException است.

تعریف: "Tasks can easily and safely be cancelled. When a task is cancelled, asyncio.CancelledError will be raised in the task at the next opportunity. It is recommended that coroutines use try/finally blocks to robustly perform clean-up logic." فراخوانی task.cancel(msg=None) فوری برمی‌گردد. task.cancelled() فقط وقتی درست است که خطا از Task بیرون رفته باشد. Task بدون await، مانند حلقهٔ CPU، تا رسیدن به await قابل لغو نیست. نسخهٔ 3.11 برای کتابخانه‌های نیازمند شمارش درخواست لغو، Task.cancelling() و Task.uncancel() را افزود. رفتار asyncio.shield(aw) چنین است: "if the coroutine containing it is cancelled, the Task running in something() is not cancelled. From the point of view of something(), the cancellation did not happen. Although its caller is still cancelled, so the "await" expression still raises a CancelledError." برای Task داخلی ارجاع جدا لازم دارید: "Save a reference to tasks passed to this function".

     cancel_with_cleanup (real, test_cancellation.py)
1    worker: log "started"; await asyncio.sleep(10)
2    caller: await asyncio.sleep(0.01); task.cancel()      # a request, returns at once
3    worker: CancelledError raised at the sleep -> finally: log "cleanup ran"
4    caller: await task -> raises CancelledError -> log "caller saw CancelledError"
5    task.cancelled() == True
     shield: outer cancelled -> outer.cancelled() True; inner still returns "payment committed"

سناریوی واقعی: Client قطع می‌شود و Uvicorn/Starlette در پاسخ Streaming یا رسیدگی به پیام قطع ASGI کار درخواست را لغو می‌کنند. Timeout فراخوانی کند بالادست را لغو می‌کند. خاموشی حلقه‌های پس‌زمینه را متوقف می‌کند. برداشت پرداخت که نباید نیمه‌کاره رها شود با Shield ادامه می‌یابد و کسی که Task داخلی را نگه داشته نتیجه‌اش را ثبت می‌کند.

وضعیترخدادکد درست
پاک‌سازی هنگام لغوCancelledError پشته را باز می‌کندtry/finally یا async with
ثبت لغو در Logبگیرید، ثبت کنید، دوباره پرتاب کنیدexcept CancelledError: log(); raise
می‌خواهید Task از لغو جان سالم ببردبلعیدن خطا TaskGroup/timeout را خراب می‌کنداین کار را نکنید؛ برای عملیات داخلی shield
عملیات داخلی حیاتیفراخواننده لغو، داخلی ادامه می‌دهدawait asyncio.shield(task) و نگهداری task
حلقهٔ CPU بدون awaitلغو نمی‌تواند قطعش کندawait asyncio.sleep(0) هر N تکرار یا انتقال به Process
except Exception: دور awaitCancelledError را در 3.8+ نمی‌گیردهمین درست است
except BaseException: یا except: خالیآن را می‌گیرددوباره پرتاب کنید

اصلاح / روش استفاده:

py
"""Cancellation, shielding and timeouts in asyncio and in AnyIO (the layer under Starlette)."""
from __future__ import annotations

import asyncio
import sys

import anyio


async def cancel_with_cleanup() -> list[str]:
    """task.cancel() raises CancelledError at the task's next await; finally still runs."""
    log: list[str] = []

    async def worker() -> None:
        try:
            log.append("started")
            await asyncio.sleep(10)
        finally:
            log.append("cleanup ran")  # release locks, close connections, roll back

    task = asyncio.create_task(worker())
    await asyncio.sleep(0.01)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        log.append("caller saw CancelledError")
    log.append(f"task.cancelled()={task.cancelled()}")
    return log


async def swallowed_cancel() -> bool:
    """BAD: catching CancelledError and not re-raising makes the task look successful."""

    async def stubborn() -> str:
        try:
            await asyncio.sleep(10)
        except asyncio.CancelledError:
            return "ignored the cancel"  # the bug: no `raise`
        return "finished"

    task = asyncio.create_task(stubborn())
    await asyncio.sleep(0.01)
    task.cancel()
    result = await task
    return task.cancelled() is False and result == "ignored the cancel"


async def shield_keeps_inner_running() -> tuple[bool, str]:
    """shield(): the outer await is cancelled, the inner task keeps going."""
    inner = asyncio.create_task(asyncio.sleep(0.05, result="payment committed"))

    async def caller() -> str:
        return await asyncio.shield(inner)  # e.g. a request handler awaiting a commit

    outer = asyncio.create_task(caller())
    await asyncio.sleep(0.01)
    outer.cancel()
    try:
        await outer
    except asyncio.CancelledError:
        pass
    return outer.cancelled(), await inner


async def wait_for_timeout(delay: float, timeout: float) -> str:
    """wait_for() cancels the awaitable on timeout and raises TimeoutError.

    On 3.9-3.10 the exception is asyncio.TimeoutError (a different class); since 3.11 it is an
    alias of the builtin TimeoutError. Catching asyncio.TimeoutError works on every version.
    """
    try:
        return await asyncio.wait_for(asyncio.sleep(delay, result="done"), timeout)
    except asyncio.TimeoutError:
        return "timed out"


async def timeout_block(delay: float, budget: float) -> str:
    """Python 3.11+: asyncio.timeout() bounds a whole block, not one awaitable."""
    if sys.version_info < (3, 11):  # pragma: no cover
        raise RuntimeError("asyncio.timeout() needs Python 3.11+")
    try:
        async with asyncio.timeout(budget):  # type: ignore[attr-defined]
            await asyncio.sleep(delay / 2)
            await asyncio.sleep(delay / 2)
            return "done"
    except TimeoutError:
        return "timed out"


async def anyio_move_on_after(delay: float, budget: float) -> tuple[str, bool]:
    """AnyIO cancel scope: leave the block quietly when the deadline passes (runs on 3.9)."""
    result = "timed out"
    with anyio.move_on_after(budget) as scope:
        await anyio.sleep(delay)
        result = "done"
    return result, scope.cancelled_caught


async def anyio_fail_after(delay: float, budget: float) -> str:
    """fail_after(): same scope, but raises TimeoutError at the deadline."""
    try:
        with anyio.fail_after(budget):
            await anyio.sleep(delay)
        return "done"
    except TimeoutError:
        return "timed out"


async def anyio_group_cancels_siblings() -> list[str]:
    """Structured concurrency on 3.9: an AnyIO task group cancels siblings on failure."""
    cancelled: list[str] = []

    async def slow(name: str) -> None:
        try:
            await anyio.sleep(1)
        except anyio.get_cancelled_exc_class():
            cancelled.append(name)
            raise

    async def broken() -> None:
        await anyio.sleep(0.01)
        raise ValueError("upstream 500")

    try:
        async with anyio.create_task_group() as tg:
            tg.start_soon(slow, "b")
            tg.start_soon(slow, "c")
            tg.start_soon(broken)
    except Exception as eg:  # ExceptionGroup (backport package on 3.9/3.10)
        cancelled.append(type(eg).__name__ + ": " + str(eg.exceptions[0]))  # type: ignore[attr-defined]
    return sorted(cancelled)
py
from __future__ import annotations

import asyncio

import pytest

from app import cancellation as c
from tests.conftest import needs_311


@pytest.mark.asyncio
async def test_cancel_runs_finally_and_propagates() -> None:
    assert await c.cancel_with_cleanup() == [
        "started",
        "cleanup ran",
        "caller saw CancelledError",
        "task.cancelled()=True",
    ]


@pytest.mark.asyncio
async def test_swallowing_cancelled_error_hides_the_cancel() -> None:
    assert await c.swallowed_cancel() is True


@pytest.mark.asyncio
async def test_shield_protects_inner_task() -> None:
    outer_cancelled, inner_result = await c.shield_keeps_inner_running()
    assert outer_cancelled is True
    assert inner_result == "payment committed"


@pytest.mark.asyncio
async def test_wait_for() -> None:
    assert await c.wait_for_timeout(0.01, 0.5) == "done"
    assert await c.wait_for_timeout(0.5, 0.02) == "timed out"


def test_timeout_error_class_on_this_python() -> None:
    import sys

    # 3.11+: asyncio.TimeoutError is TimeoutError. 3.9/3.10: two different classes.
    assert (asyncio.TimeoutError is TimeoutError) == (sys.version_info >= (3, 11))


@needs_311
@pytest.mark.asyncio
async def test_asyncio_timeout_block() -> None:  # expected on 3.11+
    assert await c.timeout_block(0.01, 0.5) == "done"
    assert await c.timeout_block(0.5, 0.05) == "timed out"


@pytest.mark.anyio
async def test_anyio_move_on_after() -> None:
    assert await c.anyio_move_on_after(0.01, 0.5) == ("done", False)
    assert await c.anyio_move_on_after(0.5, 0.02) == ("timed out", True)


@pytest.mark.anyio
async def test_anyio_fail_after() -> None:
    assert await c.anyio_fail_after(0.5, 0.02) == "timed out"


@pytest.mark.anyio
async def test_anyio_task_group_cancels_siblings() -> None:
    assert await c.anyio_group_cancels_siblings() == ["ExceptionGroup: upstream 500", "b", "c"]


@pytest.fixture
def anyio_backend() -> str:
    return "asyncio"  # run the AnyIO-marked tests on asyncio only (trio is not installed)

مهلت (Timeout): wait_for و asyncio.timeout حیاتی ​

به زبان ساده: مهلت (Timeout) یعنی «اگر بیش از N ثانیه شد لغوش کن و خبر بده». wait_for روی یک Awaitable محدودیت می‌گذارد؛ asyncio.timeout() در 3.11+ روی کل بلوک.

بدفهمی رایج: «except TimeoutError در همهٔ نسخه‌ها Timeoutهای asyncio را می‌گیرد.» در 3.9 و 3.10، asyncio.wait_for، کلاس متفاوت asyncio.TimeoutError را پرتاب می‌کند؛ نتیجهٔ واقعی 3.9: asyncio.TimeoutError is TimeoutError: False. از 3.11 یکی شده‌اند: "This class was made an alias of TimeoutError". برای پشتیبانی هر ۲، asyncio.TimeoutError را بگیرید. همچنین مهلت Client یعنی httpx.Timeout و Timeout در asyncio ۲ لایه‌اند؛ معمولاً هر ۲ را می‌خواهید.

تعریف: دربارهٔ asyncio.wait_for(aw, timeout) مستندات می‌گویند: "If a timeout occurs, it cancels aw and raises TimeoutError" و "The function will wait until the future is actually cancelled, so the total wait time may exceed the timeout". از 3.7 پیش از پرتاب خطا منتظر تکمیل لغو می‌ماند؛ از 3.12: "Implemented using asyncio.timeout()". در 3.11+، async with asyncio.timeout(delay) کار Task جاری در بلوک را هنگام سررسید لغو می‌کند و در خروج بلوک CancelledError را به TimeoutError تبدیل می‌کند. Timeout.reschedule() سررسید را عوض می‌کند و asyncio.timeout_at(when) زمان مطلق حلقه می‌گیرد. همتاهای AnyIO روی همهٔ نسخه‌ها کار می‌کنند: fail_after(seconds)، TimeoutError می‌دهد و move_on_after(seconds) بی‌صدا خارج می‌شود و scope.cancelled_caught را تنظیم می‌کند.

     wait_for(asyncio.sleep(0.5), 0.02)  (real)            asyncio.timeout(0.05) around 2 x sleep(0.25)  (expected, 3.11+)
1    t=0     inner awaitable wrapped and started            t=0     block starts, deadline = now + 50 ms
2    t=20ms  deadline: inner cancelled                      t=50ms  deadline: current task cancelled at its await
3            wait_for waits for the cancel to complete              CancelledError unwinds the block
4            raises asyncio.TimeoutError -> "timed out"             __aexit__ turns it into TimeoutError -> "timed out"
     anyio.move_on_after(0.02) around sleep(0.5) -> ("timed out", cancelled_caught=True)  (real)

سناریوی واقعی: برای هر فراخوانی بالادست ۳۰۰ ms در بودجهٔ ۱ ثانیه‌ای درخواست می‌گذارید. Query نباید اتصال Pool را بی‌نهایت نگه دارد. Health check به‌جای آویزان‌شدن «افت‌کرده» گزارش می‌دهد. برنامهٔ بعد، asyncio.TimeoutError از wait_for را به 504 تبدیل می‌کند؛ تست واقعی delay_ms=500, timeout_s=0.1 پاسخ 504 با upstream: ... داد.

APIحوزه (Scope)هنگام پایان مهلتنسخهنکته
asyncio.wait_for(aw, t)یک Awaitableلغو و TimeoutErrorهمه؛ از 3.11 نام مستعار داخلیپیش از 3.12 Coroutine را در Task می‌گذارد
async with asyncio.timeout(t)بلوکلغو بلوک و TimeoutError3.11+reschedule()، timeout_at()
asyncio.wait(aws, timeout=t)Set(done, pending)؛ بدون لغوهمهبدون استثنا
anyio.fail_after(t)بلوک یا Cancel scopeTimeoutErrorAnyIO 3+روی 3.9 کار می‌کند
anyio.move_on_after(t)بلوکخروج بی‌صدا و scope.cancelled_caughtAnyIO 3+جایگزین‌های Best effort
httpx.Timeout(t, connect=...)یک مرحلهٔ درخواست HTTPزیرکلاس‌های httpx.TimeoutExceptionhttpxپیش‌فرض "5 seconds of network inactivity"
Uvicorn --timeout-graceful-shutdownخاموشی سرورخروج اجباریUvicornخاموشی

اصلاح / روش استفاده: هر فراخوانی خروجی Timeout در Client و هر درخواست بودجهٔ کلی داشته باشد؛ asyncio.timeout در 3.11+ و پیش از آن wait_for یا fail_after در AnyIO. اگر 3.10 یا قدیمی‌تر را پشتیبانی می‌کنید asyncio.TimeoutError بگیرید. CancelledError داخلی سازوکار Timeout را نگیرید.

هم‌روندی ساخت‌یافته (Structured concurrency) با AnyIO: Task group و Cancel scope مهم ​

به زبان ساده: AnyIO ابزارهای هم‌روندی ساخت‌یافته (Structured concurrency) را برای asyncio و Trio می‌دهد؛ asyncio تازه در 3.11 بخشی از آن‌ها را گرفت و هنوز بعضی را ندارد: حوزهٔ لغو (Cancel scope) تودرتو، قابل لغو و Shield و مهلت‌های بلوکی. Starlette و FastAPI درون خود از AnyIO استفاده می‌کنند، پس در هر پروژهٔ FastAPI نصب است.

بدفهمی رایج: «Cancellation در AnyIO عین asyncio است.» AnyIO داخل Scope لغو سطحی (Level cancellation) دارد: "as long as a task remains within an effectively cancelled cancel scope, it will get hit with a cancellation exception any time it hits a yield point". asyncio لغو لبه‌ای (Edge cancellation) دارد: "a CancelledError is raised in the task and the task then gets to handle it however it likes, even opting to ignore it entirely". کدی که یک لغو را ببلعد در AnyIO هنگام await بعدی دوباره لغو می‌شود.

تعریف: مستندات AnyIO: "Cancellation in AnyIO follows the model established by the Trio framework. This means that cancellation of tasks is done via so called cancel scopes. Cancel scopes are used as context managers and can be nested. Cancelling a cancel scope cancels all cancel scopes nested within it." و "A task group contains its own cancel scope." APIها: anyio.create_task_group()، tg.start_soon(fn, *args)، await tg.start(fn) برای انتظار اعلام آمادگی فرزند، tg.cancel_scope.cancel()، anyio.CancelScope(shield=True)، fail_after، move_on_after، anyio.get_cancelled_exc_class()، anyio.to_thread.run_sync و anyio.from_thread.run. FastAPI می‌گوید: "Starlette (and FastAPI) are based on AnyIO, which makes it compatible with both Python's standard library asyncio and Trio."

     anyio task group, one child fails (real on 3.9, cancellation.anyio_group_cancels_siblings)
1    tg.start_soon(slow, "b"); tg.start_soon(slow, "c"); tg.start_soon(broken)
2    t=10ms  broken raises ValueError("upstream 500")
3            the group's cancel scope is cancelled -> b and c get the cancel exception at their sleep
4            b and c log "cancelled" and re-raise
5            group exits: ExceptionGroup("...", [ValueError("upstream 500")])
     -> ["ExceptionGroup: upstream 500", "b", "c"]

سناریوی واقعی: کتابخانه باید روی asyncio و Trio کار کند. Dependency در FastAPI برای عمر درخواست Task کمکی می‌سازد. Endpoint تدریجی هم بالادست و هم پیام قطع Client را می‌خواند و باید هر ۲ را با هم متوقف کند. Worker حتی هنگام خاموشی باید Commit پایگاه داده را تمام کند؛ CancelScope(shield=True) دور Commit قرار می‌گیرد.

مفهومasyncio از 3.11+AnyIO 4 روی 3.9+
Task groupasyncio.TaskGroup، tg.create_task(coro)anyio.create_task_group()، tg.start_soon(fn, *args)
انتظار آمادگی فرزندEvent دستیawait tg.start(fn) و task_status.started()
بلوک Timeoutasyncio.timeout(t)fail_after(t) / move_on_after(t)
محافظت (Shield)asyncio.shield(aw) برای یک AwaitableCancelScope(shield=True) برای بلوک
معنای لغوEdgeLevel در Scope
استثنای لغوasyncio.CancelledErroranyio.get_cancelled_exc_class() از Backend
Threadهاasyncio.to_thread؛ Executor پیش‌فرضanyio.to_thread.run_sync؛ CapacityLimiter با 40 توکن
تستpytest-asyncioافزونهٔ داخلی pytest و @pytest.mark.anyio

اصلاح / روش استفاده: anyio_move_on_after، anyio_fail_after و anyio_group_cancels_siblings در app/cancellation.py بالا، همگی با @pytest.mark.anyio روی 3.9 اجرا شدند. در کتابخانه‌ها و پشتیبانی Python پیش از 3.11 از AnyIO استفاده کنید؛ برای کد برنامه در 3.11+ اگر کتابخانهٔ استاندارد را ترجیح می‌دهید، asyncio معمولی مناسب است.

ابزارهای همگام‌سازی (Synchronisation primitives): Lock، Semaphore، Event و Condition مهم ​

به زبان ساده: حتی روی ۱ ریسمان (Thread)، هر await که واقعاً معلق شود، مثل I/O، Timer، asyncio.sleep(0) یا قفل در اختیار دیگری، اجرای Taskها را درهم می‌کند. اگر Task وضعیت مشترک را بخواند، await کند و بعد بنویسد، دیگری در این فاصله می‌تواند آن را تغییر دهد. asyncio ابزارهای مشابه threading دارد اما فقط بین Taskهای ۱ حلقه کار می‌کنند.

بدفهمی رایج: «۱ Thread یعنی نبود Race condition.» تابع lost_update(use_lock=False) ۵۰ واریز ۱ واحدی را با await بین خواندن و نوشتن اجرا می‌کند و موجودی ۱ می‌شود؛ ۴۹ به‌روزرسانی از دست می‌رود. با قفل (Lock) یعنی asyncio.Lock دور خواندن-await-نوشتن، نتیجه ۵۰ است. این ابزارها قفل Thread نیستند: "asyncio primitives are not thread-safe, therefore they should not be used for OS thread synchronization (use threading for that)".

تعریف: asyncio.Lock: "Implements a mutex lock for asyncio tasks. Not thread-safe." شمارندهٔ مجوز (Semaphore) در asyncio.Semaphore(value) و BoundedSemaphore حداکثر value دارنده می‌دهد. رویداد (Event) در asyncio.Event دارای set()، clear() و await wait() است: "An event object. Not thread-safe." شرط (Condition) در asyncio.Condition، await wait()، await wait_for(predicate)، notify(n) و notify_all() را زیر قفل خودش می‌دهد. مانع (Barrier) یعنی asyncio.Barrier(parties) از 3.11+ است. Lock، Semaphore، Condition و Barrier با async with کار می‌کنند؛ برای آخری async with barrier as position:. Event، Context manager نیست. در 3.9 ابزار به حلقهٔ زمان ساخت وابسته می‌شود: self._loop = events.get_event_loop() در locks.py. نسخهٔ 3.10 پارامتر loop را حذف کرد؛ ابزارها را داخل Coroutine یا Lifespan بسازید، نه هنگام import ماژولی که چند حلقه، مثلاً در تست، استفاده می‌کنند.

     lost update on ONE thread (real, coordination.lost_update)
1    task 1: current = balance (0)      ; await asyncio.sleep(0)  -- yields
2    task 2: current = balance (0)      ; await ...               -- yields
3    ...  all 50 tasks read 0 before anyone writes
4    task 1: balance = 0 + 1
5    task 2: balance = 0 + 1   ... -> final balance 1, expected 50
     with `async with lock:` around read-await-write -> 50

سناریوی واقعی: ۳۰ درخواست هم‌زمان Token منقضی OAuth می‌بینند؛ Lock با بررسی دوباره فقط ۱ تازه‌سازی انجام می‌دهد، یعنی Single flight. فراخوانی API شریک به ۵ کار هم‌زمان با Semaphore محدود می‌شود. Workerها با Event تا بارگذاری تنظیمات صبر می‌کنند. Cache با Condition منتظر «حداقل N عضو» می‌ماند. خزنده هم برای رعایت سقف سرویس از این ابزارها استفاده می‌کند.

ابزارظرفیت / محتواکاربرد معمولامن برای Thread؟از نسخهٔ
asyncio.Lock1 Taskبخش بحرانی با await داخلینه3.4
asyncio.Semaphore(n)n Taskسقف هم‌روندی و بودجهٔ اتصالنه3.4
asyncio.BoundedSemaphore(n)n؛ خطا در release اضافیهمان، با کشف باگنه3.4
asyncio.Eventپرچمسیگنال یک‌به‌چندنه3.4
asyncio.Conditionقفل و صف انتظارانتظار شرط روی وضعیت مشترکنه3.4
asyncio.Barrier(n)n ورودهماهنگی مرحله‌هانه3.11
threading.Lock1 Threadوضعیت مشترک با Worker Threadبلهندارد
anyio.Lock، anyio.Semaphore، CapacityLimiterمانند بالاکد مستقل از BackendنهAnyIO

اصلاح / روش استفاده: وضعیت مشترک تغییرپذیر را کوچک نگه دارید. عملیات اتمی بدون await بین خواندن و نوشتن را ترجیح بدهید؛ اگر await اجتناب‌ناپذیر است، asyncio.Lock بگیرید. وضعیت مشترک با Threadها threading.Lock می‌خواهد یا تحویل مقدار به حلقه با loop.call_soon_threadsafe. شکل پایگاه‌داده‌ای این باگ به‌روزرسانی گم‌شده است و با SQL اصلاح می‌شود، نه قفل درون Process.

صف (Queue)، تولیدکننده/مصرف‌کننده (Producer/consumer) و پس‌فشار (Back-pressure) مهم ​

به زبان ساده: asyncio.Queue بافر میان Task تولیدکننده و مصرف‌کننده است. اگر سقف اندازه بدهید، تولیدکنندهٔ سریع هنگام پرشدن منتظر می‌ماند و به سرعت مصرف‌کننده محدود می‌شود؛ کار در حافظه انباشته نمی‌شود. این انتظار همان پس‌فشار (Back-pressure) است.

بدفهمی رایج: «صف نامحدود امن‌تر است چون هیچ کاری رد نمی‌شود.» مصرف‌کنندهٔ کند در صف نامحدود رشد بی‌سقف حافظه و تأخیر می‌سازد. سقف همراه سیاست انتظار، دورریختن یا ردکردن با 503/429 سرویس را زیر بار زنده نگه می‌دارد.

تعریف: asyncio.Queue(maxsize=0) به‌طور پیش‌فرض نامحدود است. await put(item) هنگام پر بودن منتظر می‌ماند؛ put_nowait، QueueFull می‌دهد؛ این خطا واقعاً مشاهده شد. await get() در صف خالی منتظر می‌ماند. task_done() پردازش یک عضو را اعلام می‌کند و await join() منتظر علامت‌خوردن همهٔ ورودی‌ها می‌ماند. qsize()، full() و empty() هم وجود دارند؛ همچنین PriorityQueue و LifoQueue. نسخهٔ 3.13، Queue.shutdown(immediate=False) و QueueShutDown را افزود: "Raises QueueShutDown if the queue has been shut down". این جای نشانهٔ پایان (Sentinel) را می‌گیرد؛ در 3.9 خروجی واقعی hasattr Queue.shutdown: False است، پس مانند قطعه‌کد برای هر مصرف‌کننده یک Sentinel می‌گذارید. Queue هم Thread-safe نیست؛ از Thread، loop.call_soon_threadsafe(q.put_nowait, x) به کار ببرید.

     maxsize=5, 40 items, 4 consumers x 10 ms each (real, coordination.producer_consumer)
1    producer: put 0..4   -> queue full
2    producer: put(5) waits ...                    consumers: get 0,1,2,3 ; sleep 10 ms
3    consumers task_done -> space -> producer resumes, refills
4    ... producer total waiting time 0.088 s; qsize never above 5
5    producer: put(None) x 4  (one sentinel per consumer)
6    consumers exit; await queue.join() returns
     -> {'processed': 40, 'max_qsize': 5, 'producer_wait_s': 0.088, 'elapsed_s': 0.11}

سناریوی واقعی: گیرندهٔ Webhook رویداد را سریع می‌پذیرد و با سرعت پایگاه داده می‌نویسد. خزنده صف URL و N دریافت‌کننده دارد. ارسال‌کنندهٔ Log خط‌ها را دسته‌ای به API می‌فرستد. پخش‌کنندهٔ WebSocket برای هر Client صف محدود دارد و Client کند را حذف یا قطع می‌کند.

سیاست هنگام پرشدنروشمناسب برای
انتظار تولیدکننده؛ Back-pressureawait q.put(x)تولیدکنندهٔ قابل کندشدن، مثل Pipeline داخلی
رد درخواستq.put_nowait(x) → QueueFull → 503 / 429Client دارای امکان Retry
حذف جدیدترین / قدیمی‌ترینput_nowait در try یا get_nowait() سپس putسنجه، Telemetry، قیمت زنده
قطع مصرف‌کنندهٔ کندپرشدن صف Client → بستنWebSocket و Fan-out در SSE
ذخیرهٔ پایدارRedis Streams، RabbitMQ، Kafka، SQSنیاز به بقا پس از Restart؛ پیام‌رسانی

اصلاح / روش استفاده:

py
"""Lock, Semaphore, Event, Condition and Queue: coordination between tasks on ONE loop."""
from __future__ import annotations

import asyncio
import time


async def lost_update(use_lock: bool, workers: int = 50) -> int:
    """A read-await-write sequence loses updates without a Lock, even on one thread."""
    balance = {"value": 0}
    lock = asyncio.Lock()  # create primitives inside a coroutine (3.9 binds them to a loop)

    async def deposit() -> None:
        if use_lock:
            async with lock:
                current = balance["value"]
                await asyncio.sleep(0)  # e.g. a DB round trip between read and write
                balance["value"] = current + 1
        else:
            current = balance["value"]
            await asyncio.sleep(0)
            balance["value"] = current + 1

    await asyncio.gather(*(deposit() for _ in range(workers)))
    return balance["value"]


async def semaphore_peak(limit: int, jobs: int) -> int:
    """At most `limit` coroutines inside the `async with sem` block at any moment."""
    sem = asyncio.Semaphore(limit)
    inside = peak = 0

    async def job() -> None:
        nonlocal inside, peak
        async with sem:
            inside += 1
            peak = max(peak, inside)
            await asyncio.sleep(0.01)
            inside -= 1

    await asyncio.gather(*(job() for _ in range(jobs)))
    return peak


async def event_gate() -> list[str]:
    """Event: many waiters released by one set() (e.g. 'config loaded', 'shutdown started')."""
    ready = asyncio.Event()
    log: list[str] = []

    async def waiter(name: str) -> None:
        await ready.wait()
        log.append(f"{name} released")

    tasks = [asyncio.create_task(waiter(n)) for n in ("w1", "w2")]
    await asyncio.sleep(0.01)
    log.append("set()")
    ready.set()
    await asyncio.gather(*tasks)
    return log


async def condition_handoff() -> list[int]:
    """Condition: wait until a predicate over shared state is true, under a lock."""
    cond = asyncio.Condition()
    items: list[int] = []
    got: list[int] = []

    async def consumer() -> None:
        async with cond:
            await cond.wait_for(lambda: len(items) >= 3)
            got.extend(items)

    task = asyncio.create_task(consumer())
    for i in range(3):
        async with cond:
            items.append(i)
            cond.notify_all()
        await asyncio.sleep(0)
    await task
    return got


async def producer_consumer(maxsize: int, items: int, consumers: int, work: float) -> dict[str, float]:
    """Bounded Queue = back-pressure: put() waits while the queue is full."""
    queue: asyncio.Queue[int | None] = asyncio.Queue(maxsize=maxsize)
    processed: list[int] = []
    max_seen = 0
    producer_wait = 0.0

    async def producer() -> None:
        nonlocal max_seen, producer_wait
        for i in range(items):
            t0 = time.perf_counter()
            await queue.put(i)  # blocks when consumers are behind
            producer_wait += time.perf_counter() - t0
            max_seen = max(max_seen, queue.qsize())
        for _ in range(consumers):
            await queue.put(None)  # one sentinel per consumer: "no more work"

    async def consumer() -> None:
        while True:
            item = await queue.get()
            try:
                if item is None:
                    return
                await asyncio.sleep(work)
                processed.append(item)
            finally:
                queue.task_done()

    start = time.perf_counter()
    await asyncio.gather(producer(), *(consumer() for _ in range(consumers)))
    await queue.join()  # every put() has a matching task_done()
    return {
        "processed": len(processed),
        "max_qsize": max_seen,
        "producer_wait_s": round(producer_wait, 3),
        "elapsed_s": round(time.perf_counter() - start, 3),
    }
py
from __future__ import annotations

import pytest

from app import coordination as co


@pytest.mark.asyncio
async def test_lost_update_without_lock() -> None:
    assert await co.lost_update(use_lock=False, workers=50) == 1  # 49 updates lost
    assert await co.lost_update(use_lock=True, workers=50) == 50


@pytest.mark.asyncio
async def test_semaphore_caps_concurrency() -> None:
    assert await co.semaphore_peak(limit=3, jobs=12) == 3


@pytest.mark.asyncio
async def test_event_releases_all_waiters() -> None:
    assert await co.event_gate() == ["set()", "w1 released", "w2 released"]


@pytest.mark.asyncio
async def test_condition_wait_for_predicate() -> None:
    assert await co.condition_handoff() == [0, 1, 2]


@pytest.mark.asyncio
async def test_bounded_queue_applies_back_pressure(capsys: pytest.CaptureFixture[str]) -> None:
    stats = await co.producer_consumer(maxsize=5, items=40, consumers=4, work=0.01)
    print(f"\nqueue maxsize=5, 40 items, 4 consumers x 10 ms: {stats}")
    assert stats["processed"] == 40
    assert stats["max_qsize"] <= 5  # never more than maxsize buffered
    assert stats["producer_wait_s"] > 0.05  # the producer was slowed to the consumers' pace
Getting blocking work off the event loop threadEvent loop threadasync def routes, taskshttpx.AsyncClient, asyncpgawait asyncio.to_thread(f)loop.run_in_executor(None, f)def route (FastAPI)await run_in_threadpool(f)loop.run_in_executor(process_pool, cpu_job)awaits a Future meanwhileDefault ThreadPoolExecutormax_workers = min(32, cpu_count + 4)16 on a 12-core Mac (measured)contextvars copied by to_threadAnyIO worker threadsCapacityLimiter: 40 tokensshared by def routes, sync deps,FileResponse, run_in_threadpoolProcessPoolExecutorone interpreter + GIL per workerargs/results pickled; spawn costGood for threadssync DB driversrequests, boto3file I/O, sqlite3C code that releasesthe GIL (hashlib, zlib)the GIL is releasedwhile a thread waitson I/OPure-Python CPUthreads: 0.37 s vs 0.42 s inlineprocesses: 0.18 s (4 jobs)

اجرای کد Blocking: to_thread، run_in_executor و اندازهٔ Executor پیش‌فرض حیاتی ​

به زبان ساده: اگر باید از کد Async چیزی مسدودکننده (Blocking) را صدا بزنید، آن را به Worker Thread بدهید و نتیجه را await کنید. Thread حلقه آزاد می‌ماند، Worker منتظر می‌شود و پس از پایان، حلقه Coroutine شما را با مقدار بازگشتی ادامه می‌دهد.

بدفهمی رایج: «Thread pool نامحدود است؛ همه‌چیز را به آن بسپاریم.» Executor پیش‌فرض اندازهٔ ثابت دارد؛ اینجا روی ماشین ۱۲ هسته‌ای ۱۶ Worker اندازه‌گیری شد و همهٔ to_threadها آن را شریک‌اند. اگر ۱۶ فراخوانی در سرور کند گیر کنند، فراخوانی شمارهٔ ۱۷ در صف Executor منتظر می‌ماند، درحالی‌که حلقه کاملاً سالم به نظر می‌رسد. Routeهای def در FastAPI اصلاً از این Executor استفاده نمی‌کنند؛ محدودکنندهٔ AnyIO با ۴۰ توکن دارند، طبق اندازه‌گیری. اندازهٔ Pool را متناسب کار Blocking واقعی انتخاب کنید و به وابستگی کند Executor مستقل بدهید.

تعریف: asyncio.to_thread(func, /, *args, **kwargs) از 3.9+: "Asynchronously run function func in a separate thread … the current contextvars.Context is propagated, allowing context variables from the event loop thread to be accessed in the separate thread." در CPython 3.9 ۳ قدم دارد: کپی Context، ساخت functools.partial(ctx.run, func, ...) و await loop.run_in_executor(None, func_call). تابع loop.run_in_executor(executor, func, *args) یک asyncio Future می‌دهد؛ executor=None یعنی ThreadPoolExecutor پیش‌فرض حلقه که در اولین استفاده ساخته می‌شود. اندازه‌اش طبق مستندات: "Changed in version 3.8: Default value of max_workers is changed to min(32, os.cpu_count() + 4)". در نسخه‌های جاری فرمول min(32, (os.process_cpu_count() or 1) + 4) است: "Changed in version 3.13"؛ process_cpu_count فقط CPUهای مجاز Process را می‌شمارد. loop.set_default_executor(ThreadPoolExecutor(max_workers=n)) آن را جایگزین می‌کند. loop.shutdown_default_executor() که asyncio.run هنگام خروج صدا می‌زند، منتظر پایان Threadها می‌ماند. یادآوری مستندات: "Due to the GIL, asyncio.to_thread() can typically only be used to make IO-bound functions non-blocking."

     await asyncio.to_thread(query_orders, db, 1)    (CPython 3.9 threads.py)
1    loop thread: ctx = contextvars.copy_context()
2    loop thread: fut = loop.run_in_executor(None, partial(ctx.run, query_orders, db, 1))
3    loop thread: await fut  -> task suspended, loop serves other tasks
4    worker thread "asyncio_0": runs sqlite3 query (GIL released while waiting on I/O)
5    worker thread: result ready -> loop.call_soon_threadsafe(set result on fut)
6    loop thread: task resumes with the rows
     default executor: min(32, cpu_count + 4) = min(32, 12 + 4) = 16 (real)

سناریوی واقعی: SDK همگام مانند boto3 یا Client پرداخت داخل سرویس Async؛ sqlite3 یا psycopg2 در برنامهٔ کوچکی که بقیه‌اش Async است؛ خواندن فایل بزرگ یا محاسبهٔ Checksum با hashlib که GIL را آزاد می‌کند؛ ماژول قدیمی که این فصل امکان بازنویسی‌اش نیست. در FastAPI ساده‌ترین برون‌سپاری (Offload)، نوشتن Route با def است؛ async def در برابر def.

فراخوانیPoolاندازهٔ پیش‌فرضکپی Context؟کاربرد
await asyncio.to_thread(f, *a)ThreadPoolExecutor پیش‌فرض حلقهmin(32, cpu + 4)بلهI/O Blocking در asyncio
await loop.run_in_executor(None, f, *a)همانهماننه؛ خودتان ctx.run بگذاریدپیش از 3.9؛ آرگومان نام‌دار با partial
await loop.run_in_executor(my_pool, f)Executor خودتانانتخاب شمانهجداسازی وابستگی کند
await anyio.to_thread.run_sync(f)Threadهای Worker در AnyIO40 توکن؛ CapacityLimiterبلهکد AnyIO / Starlette
await starlette.concurrency.run_in_threadpool(f, *a)Threadهای Worker در AnyIO40 توکنبلهداخل Route با async def؛ نام واقعی Thread: AnyIO worker thread
Route با def یا Dependency همگام FastAPIThreadهای Worker در AnyIO40 توکنبلهتمام Route همگام است
loop.run_in_executor(ProcessPoolExecutor(), f)Processهاos.process_cpu_count() از 3.13+نه؛ Pickle می‌شودکار CPU-bound

اصلاح / روش استفاده:

py
"""Blocking calls, the default executor, to_thread, run_in_executor, thread vs process pools."""
from __future__ import annotations

import asyncio
import concurrent.futures
import functools
import os
import sqlite3
import sys
import time


async def heartbeat_lag(blocker: str, seconds: float = 0.2) -> float:
    """Run a 10 ms heartbeat next to a 'blocking' job; return the worst gap between beats.

    blocker="time.sleep" blocks the loop thread, so the heartbeat stalls for the whole job.
    blocker="to_thread" runs the same time.sleep in the default executor: the loop stays free.
    blocker="asyncio.sleep" never blocks at all.
    """
    gaps: list[float] = []
    stop = asyncio.Event()

    async def heartbeat() -> None:
        last = time.perf_counter()
        while not stop.is_set():
            await asyncio.sleep(0.01)
            now = time.perf_counter()
            gaps.append(now - last)
            last = now

    async def job() -> None:
        await asyncio.sleep(0.02)  # let the heartbeat start
        if blocker == "time.sleep":
            time.sleep(seconds)  # BAD inside a coroutine: freezes every task on this loop
        elif blocker == "to_thread":
            await asyncio.to_thread(time.sleep, seconds)
        else:
            await asyncio.sleep(seconds)
        stop.set()

    await asyncio.gather(heartbeat(), job())
    return max(gaps)


def default_executor_workers() -> int:
    """The formula ThreadPoolExecutor uses when max_workers is None.

    3.8-3.12: min(32, os.cpu_count() + 4). 3.13+: os.process_cpu_count(), which counts only
    the CPUs this process may use (affinity, -X cpu_count, PYTHON_CPU_COUNT).
    """
    if sys.version_info >= (3, 13):
        cpus = os.process_cpu_count()  # type: ignore[attr-defined]
    else:
        cpus = os.cpu_count()
    return min(32, (cpus or 1) + 4)


async def default_executor_size() -> int:
    """Read the real size of the loop's default executor after the first to_thread call."""
    await asyncio.to_thread(lambda: None)
    executor = asyncio.get_running_loop()._default_executor  # private: for the demo only
    return executor._max_workers  # type: ignore[union-attr]


def query_orders(db_path: str, customer_id: int) -> list[tuple[int, int]]:
    """A blocking DB driver call (sqlite3). Never call this directly in `async def`."""
    with sqlite3.connect(db_path) as conn:
        return conn.execute(
            "SELECT id, total_cents FROM orders WHERE customer_id = ? ORDER BY id",
            (customer_id,),
        ).fetchall()


async def orders_for(db_path: str, customer_ids: list[int]) -> dict[int, list[tuple[int, int]]]:
    """Several blocking queries at once, each in a worker thread, the loop stays free."""
    rows = await asyncio.gather(*(asyncio.to_thread(query_orders, db_path, c) for c in customer_ids))
    return dict(zip(customer_ids, rows))


def cpu_burn(n: int) -> int:
    """Pure-Python CPU work: holds the GIL the whole time (module level so processes can import it)."""
    total = 0
    for i in range(n):
        total += i * i % 7
    return total


async def cpu_fanout(kind: str, jobs: int, n: int) -> float:
    """Same CPU job x `jobs`: sequential on the loop, in a thread pool, or in a process pool."""
    loop = asyncio.get_running_loop()
    start = time.perf_counter()
    if kind == "inline":
        for _ in range(jobs):
            cpu_burn(n)  # blocks the loop, shown only for the baseline
    else:
        pool_cls = (
            concurrent.futures.ThreadPoolExecutor
            if kind == "threads"
            else concurrent.futures.ProcessPoolExecutor
        )
        with pool_cls(max_workers=jobs) as pool:
            await asyncio.gather(*(loop.run_in_executor(pool, functools.partial(cpu_burn, n)) for _ in range(jobs)))
    return time.perf_counter() - start
py
from __future__ import annotations

import os
import sqlite3
import sys
from pathlib import Path

import pytest

from app import offload


@pytest.mark.asyncio
async def test_heartbeat_time_sleep_blocks_the_loop_to_thread_does_not() -> None:
    blocked = await offload.heartbeat_lag("time.sleep", 0.2)
    offloaded = await offload.heartbeat_lag("to_thread", 0.2)
    free = await offload.heartbeat_lag("asyncio.sleep", 0.2)
    print(f"\nworst heartbeat gap: time.sleep {blocked:.3f}s, to_thread {offloaded:.3f}s, asyncio.sleep {free:.3f}s")
    assert blocked >= 0.18  # the 10 ms heartbeat could not run for ~200 ms
    assert offloaded < 0.1
    assert free < 0.1


@pytest.mark.asyncio
async def test_default_executor_size_formula() -> None:
    size = await offload.default_executor_size()
    print(f"\nos.cpu_count()={os.cpu_count()} default executor max_workers={size}")
    assert size == offload.default_executor_workers()


@pytest.mark.asyncio
async def test_blocking_driver_in_threads(tmp_path: Path) -> None:
    db = tmp_path / "shop.db"
    with sqlite3.connect(db) as conn:
        conn.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, total_cents INTEGER)")
        conn.executemany(
            "INSERT INTO orders (customer_id, total_cents) VALUES (?, ?)", [(1, 1200), (2, 500), (1, 300)]
        )
    result = await offload.orders_for(str(db), [1, 2])
    assert result == {1: [(1, 1200), (3, 300)], 2: [(2, 500)]}


@pytest.mark.asyncio
async def test_cpu_bound_threads_vs_processes() -> None:
    n = 2_000_000
    inline = await offload.cpu_fanout("inline", 4, n)
    threads = await offload.cpu_fanout("threads", 4, n)
    processes = await offload.cpu_fanout("processes", 4, n)
    print(f"\n4 x cpu_burn({n}): inline {inline:.2f}s, threads {threads:.2f}s, processes {processes:.2f}s")
    assert threads > inline * 0.5  # the GIL: no 4x speed-up from 4 threads (wide margin: shared CI machines)
    if (os.cpu_count() or 1) >= 4:
        assert processes < threads  # separate interpreters, separate GILs

این SELECT را query_orders از راه Driver مسدودکننده اجرا می‌کند. با راه‌انداز Async مانند asyncpg، aiosqlite یا AsyncSession در SQLAlchemy، همین عبارت مستقیم await می‌شود و حلقه اتصال‌ها (Connections) را چندراهه می‌کند؛ برای هر Query ۱ Thread لازم نیست:

sql
-- app/offload.py query_orders(): parameterised, one round trip per customer
SELECT id, total_cents
FROM orders
WHERE customer_id = ?          -- $1 in asyncpg / PostgreSQL
ORDER BY id;

-- What "concurrent" means on the server side: three sessions from three tasks
-- (PostgreSQL; pg_sleep stands in for a slow query)
SELECT pid, state, wait_event_type, now() - query_start AS running_for, left(query, 40)
FROM pg_stat_activity
WHERE application_name = 'dashboard' AND state = 'active';

کار CPU-bound: ProcessPoolExecutor و multiprocessing مهم ​

به زبان ساده: محاسبهٔ Python خالص GIL را نگه می‌دارد؛ Threadها نوبتی اجرا می‌شوند و Event loop در طول آن متوقف است. برای استفاده از چند هسته چند پردازه (Process) با مفسر مستقل می‌خواهید.

بدفهمی رایج: «to_thread کد سنگین CPU در Route ناهمگام را حل می‌کند.» پاسخ‌گویی حلقه را فقط تا حدی حفظ می‌کند؛ Worker و حلقه برای GIL رقابت می‌کنند و شتابی ندارید. ۴ کار cpu_burn(2_000_000) در اندازه‌گیری: مستقیم روی حلقه ۰٫۴۲ ثانیه، با ۴ Thread ۰٫۳۷ ثانیه و ۴ Process ۰٫۱۸ ثانیه، شامل هزینهٔ شروع Process با روش spawn در macOS.

تعریف: concurrent.futures.ProcessPoolExecutor(max_workers=None) توابع قابل فراخوانی را در Process Worker اجرا می‌کند. مستندات جاری: "If max_workers is None or not given, it will default to os.process_cpu_count()"؛ نسخه‌های قدیمی‌تر os.cpu_count() داشتند. تابع و آرگومان باید Picklable و قابل import در فرزند باشند؛ تابع سطح ماژول مناسب است، Lambda و Closure نیستند. multiprocessing سطح پایین‌تر است: Process، Pool، Queue و روش‌های شروع fork، spawn و forkserver. از asyncio با await loop.run_in_executor(process_pool, func, arg) فراخوانی کنید. Pool را ۱ بار در Lifespan بسازید، نه در هر درخواست؛ شروع Process ده‌ها تا صدها میلی‌ثانیه هزینه دارد.

     4 x cpu_burn(2_000_000) on a 12-core Mac (real, tests/test_offload.py)
1    inline (on the loop)          0.42 s   loop blocked the whole time
2    ThreadPoolExecutor(4)         0.37 s   GIL: one thread runs bytecode at a time
3    ProcessPoolExecutor(4)        0.18 s   4 interpreters, 4 GILs, 4 cores (+ spawn cost)

سناریوی واقعی: ساخت PDF صورتحساب با Python خالص، تغییر اندازهٔ تصویر وقتی کتابخانه GIL را نگه می‌دارد، محاسبهٔ پیشنهادها برای گروه کاربران و تجزیهٔ CSV ۲۰۰ MB. برای کار چندثانیه‌ای معمولاً صف کار Celery، arq، RQ یا Dramatiq با Processهای مستقل بهتر از Pool داخل Process وب است؛ از Restart جان سالم می‌برد و برای CPU با درخواست‌ها رقابت نمی‌کند.

گزینهCPU موازیهزینهٔ شروعانتقال دادهمناسب برای
مستقیم در async defنه؛ حلقه هم بسته می‌شودنداردنداردفقط کار چندمیکروثانیه‌ای
to_thread / Thread poolنه به‌خاطر GIL، مگر C آزادش کندکمحافظهٔ مشترکافزونهٔ C آزادکنندهٔ GIL
ProcessPoolExecutor با run_in_executorبلهزیاد؛ یک بار برای هر WorkerPickleCPU از 10 ms تا چند ثانیه
multiprocessing.Pool / ProcessبلهزیادPickle، حافظهٔ مشترک و Pipeاسکریپت و کار دسته‌ای
Worker صف کاربلهکاربرد ندارد؛ بلندعمرپیام Brokerکار کند، دارای Retry یا زمان‌بندی‌شده
Free-threaded 3.14t با Threadبلهکمحافظهٔ مشترکاگر همهٔ افزونه‌ها سازگار باشند

اصلاح / روش استفاده: offload.cpu_fanout("processes", ...) بالا را ببینید. در سرویس یک ProcessPoolExecutor در Lifespan بسازید، به run_in_executor بدهید و تعداد کار CPU در جریان را با Semaphore محدود کنید تا هجوم درخواست صف بی‌سقف نسازد.

مولد ناهمگام (Async generator)، async for، async with و Async context manager مهم ​

به زبان ساده: async for حلقه‌ای است که قدم «عضو بعدی را بگیر» می‌تواند await کند؛ مثل Cursor پایگاه داده، جریان پیام یا صفحه‌های API. async with همان with با ورود و خروج قابل await است؛ مثل بازکردن اتصال (Connection)، آغاز تراکنش (Transaction) و Commit آن.

بدفهمی رایج: «وقتی حلقه تمام شد Async generator پاک‌سازی می‌شود.» با break از async for، Generator معلق می‌ماند. finally فقط با بسته‌شدن توسط aclose() اجرا می‌شود؛ اگر به جمع‌آوری حافظه یا خاموشی حلقه موکول شود، ممکن است در Task اشتباه اجرا شود یا اصلاً اجرا نشود. برای Generator دارای منبع از contextlib.aclosing() در 3.10+ یا await agen.aclose() صریح استفاده کنید.

تعریف: PEP ۵۲۵ در 3.6 مولد ناهمگام (Async generator) را معرفی کرد: async def همراه yield، پیمایش با async for و متدهای asend، athrow و aclose. PEP ۵۳۰ در 3.6، Async comprehension مانند [x async for x in agen()] و await داخل Comprehension را افزود. مدیر زمینهٔ ناهمگام (Async context manager) متدهای __aenter__ و __aexit__ دارد؛ contextlib.asynccontextmanager آن را از Async generator با ۱ yield می‌سازد: کد قبل، ورود و کد بعد، خروج است. asyncio.run و shutdown_asyncgens() هنگام بستن حلقه Generatorهای باقی‌مانده را نهایی می‌کنند.

     async with transaction(pool): raise ValueError  (real, streams.demo)
1    async with Pool() as pool        -> __aenter__: "open"
2      async with transaction(pool)   -> before yield: "BEGIN"
3        body ok                      -> after yield: "COMMIT"
4      async with transaction(pool)   -> "BEGIN"
5        body raises ValueError       -> except branch: "ROLLBACK", re-raise
6    pool __aexit__                   -> "close"
     -> ["open", "BEGIN", "COMMIT", "BEGIN", "ROLLBACK", "close"]; [i*i async for i in ticks(4) if i % 2 == 0] -> [0, 4]

سناریوی واقعی: خواندن تدریجی ردیف‌های asyncpg با Cursor سمت سرور؛ مصرف Kafka یا Redis Stream با async for msg in consumer؛ Dependency دارای yield در FastAPI، با Session قبل و Commit/Close بعد در تزریق وابستگی؛ async with httpx.AsyncClient()؛ async with engine.begin() as conn در SQLAlchemy؛ Endpoint رویداد SSE در استثنا و پاسخ.

ساختارپروتکلکاربرد کتابخانه‌ای
async for x in it__aiter__ / __anext__؛ پرتاب StopAsyncIterationCursor، مصرف‌کنندهٔ پیام، response.aiter_bytes()
Async generatorasync def + yield؛ aclose()خواندن API صفحه‌بندی‌شده، جریان SSE
[x async for x in it]Async comprehension؛ PEP 530جمع‌کردن جریان کوچک
async with cm__aenter__ / __aexit__Client، Session، Lock، Transaction، Task group
@asynccontextmanagerAsync generator با یک yieldLifespan، Fixture تست، Transaction
contextlib.AsyncExitStackمجموعهٔ پویای Context managerهای Asyncبازکردن N Client در Lifespan
contextlib.aclosing(agen)بستن Generator در خروج بلوکGenerator دارای منبع، 3.10+

اصلاح / روش استفاده:

py
"""Async generators, `async for`, `async with`, async comprehensions."""
from __future__ import annotations

import asyncio
from contextlib import asynccontextmanager
from typing import AsyncIterator


async def ticks(n: int, delay: float = 0.0) -> AsyncIterator[int]:
    """An async generator (PEP 525): `await` and `yield` in one function."""
    for i in range(n):
        await asyncio.sleep(delay)
        yield i


class Pool:
    """A fake connection pool with an explicit async context manager protocol."""

    def __init__(self) -> None:
        self.events: list[str] = []

    async def __aenter__(self) -> "Pool":
        await asyncio.sleep(0)
        self.events.append("open")
        return self

    async def __aexit__(self, *exc: object) -> None:
        await asyncio.sleep(0)
        self.events.append("close")


@asynccontextmanager
async def transaction(pool: Pool) -> AsyncIterator[str]:
    """The decorator form: code before `yield` = __aenter__, after = __aexit__."""
    pool.events.append("BEGIN")
    try:
        yield "tx"
        pool.events.append("COMMIT")
    except Exception:
        pool.events.append("ROLLBACK")
        raise


async def demo() -> tuple[list[int], list[str]]:
    squares = [i * i async for i in ticks(4) if i % 2 == 0]  # PEP 530 async comprehension
    async with Pool() as pool:
        async with transaction(pool):
            pass
        try:
            async with transaction(pool):
                raise ValueError("constraint violated")
        except ValueError:
            pass
    return squares, pool.events

contextvars میان await، Task و Thread مهم ​

به زبان ساده: ContextVar متغیری است که مقدارش به Task جاری تعلق دارد؛ شبیه ذخیره‌سازی محلی ریسمان (Thread-local storage)، اما برای هر Task. شناسهٔ درخواست را در شروع تنظیم کنید؛ همهٔ توابع آن درخواست از میان هر تعداد await همان شناسه را می‌بینند و درخواست هم‌روند شناسهٔ خودش را.

بدفهمی رایج: «threading.local() برای Async کار می‌کند.» همهٔ Taskهای حلقه ۱ Thread دارند؛ مقدار تنظیم‌شدهٔ درخواست A، به‌محض await آن برای B هم دیده می‌شود. همچنین «مقدار فرزند به والد برمی‌گردد» غلط است. هر Task در کپی Context سازنده اجرا می‌شود و تغییر فرزند همان‌جا می‌ماند؛ در اجرای واقعی فرزند set-in-child دید و والد همچنان -.

تعریف: PEP ۵۶۷ در 3.7: "This concept is similar to thread-local storage (TLS), but, unlike TLS, it also allows correctly keeping track of values per asynchronous task, e.g. asyncio.Task." با ContextVar(name, default=...) می‌سازید؛ var.set(value) یک Token می‌دهد، var.reset(token) مقدار قبلی را برمی‌گرداند و var.get() می‌خواند. contextvars.copy_context() و Context.run(fn) کد را در Context مشخص اجرا می‌کنند. asyncio هنگام ساخت Task و زمان‌بندی Callback، Context را کپی می‌کند؛ از 3.11 با create_task(..., context=) می‌توان دیگری را داد. to_thread و anyio.to_thread.run_sync آن را به Worker Thread کپی می‌کنند؛ loop.run_in_executor و threading.Thread معمولی نه. در ساخت Free-threaded، Threadها به‌طور پیش‌فرض آن را به ارث می‌برند.

     two concurrent requests (real, ctx.concurrent_requests)
1    task req-1: request_id.set("req-1"); log "start"          task req-2: request_id.set("req-2"); log "start"
2    task req-1: await sleep  (req-2 runs here, sets its own value in its own context)
3    task req-1: log "after await" -> [req-1]                  task req-2: log "after await" -> [req-2]
4    to_thread(blocking_lookup) -> worker thread sees [req-1]  ... sees [req-2]
5    finally: request_id.reset(token)  -> outside both: "-"

سناریوی واقعی: شناسهٔ Request یا Trace در هر خط Log با structlog یا logging.Filter؛ مستأجر (Tenant) جاری در برنامهٔ چندمستأجری؛ Span جاری OpenTelemetry در ContextVar؛ یافتن Session هر درخواست در بعضی Frameworkها؛ انتقال ضمنی بودجهٔ زمانی به همهٔ فراخوانی‌های خروجی.

سازوکاربرای هر Threadبرای هر Taskکپی در to_threadکپی در run_in_executor
متغیر سراسرینهنهکاربرد نداردکاربرد ندارد
threading.local()بلهنه؛ مشترک بین Taskهای حلقهنهنه
ContextVarبلهبلهبلهنه؛ ctx.run بگذارید
پارامتر صریحکاربرد نداردبلهبلهبله

اصلاح / روش استفاده:

py
"""contextvars across awaits, tasks and threads: per-request state without globals."""
from __future__ import annotations

import asyncio
import contextvars

request_id: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")


def log(msg: str) -> str:
    # Deep in the call stack, no parameter threading needed.
    return f"[{request_id.get()}] {msg}"


def blocking_lookup() -> str:
    return log("in worker thread")


async def handle(rid: str) -> list[str]:
    token = request_id.set(rid)
    try:
        lines = [log("start")]
        await asyncio.sleep(0.01)  # other requests run here; our value is not overwritten
        lines.append(log("after await"))
        lines.append(await asyncio.to_thread(blocking_lookup))  # to_thread copies the context
        return lines
    finally:
        request_id.reset(token)


async def concurrent_requests() -> list[list[str]]:
    # Each task created by gather() runs in a COPY of the current context.
    return list(await asyncio.gather(handle("req-1"), handle("req-2")))


async def child_changes_do_not_leak() -> tuple[str, str]:
    """A task sets the variable in its own context copy; the parent does not see it."""

    async def child() -> str:
        request_id.set("set-in-child")
        return request_id.get()

    seen_in_child = await asyncio.create_task(child())
    return seen_in_child, request_id.get()
py
from __future__ import annotations

import pytest

from app import ctx, streams


@pytest.mark.asyncio
async def test_context_var_survives_awaits_and_threads() -> None:
    assert await ctx.concurrent_requests() == [
        ["[req-1] start", "[req-1] after await", "[req-1] in worker thread"],
        ["[req-2] start", "[req-2] after await", "[req-2] in worker thread"],
    ]
    assert ctx.request_id.get() == "-"


@pytest.mark.asyncio
async def test_task_context_is_a_copy() -> None:
    assert await ctx.child_changes_do_not_leak() == ("set-in-child", "-")


@pytest.mark.asyncio
async def test_async_generators_and_context_managers() -> None:
    squares, events = await streams.demo()
    assert squares == [0, 4]
    assert events == ["open", "BEGIN", "COMMIT", "BEGIN", "ROLLBACK", "close"]

نقطهٔ ورود (Entry point): asyncio.run، loop.run_until_complete، Runner و nest_asyncio تکمیلی ​

به زبان ساده: یک کد همگام (Sync) باید حلقه را آغاز کند. در اسکریپت asyncio.run(main()) است، در سرور Uvicorn، در تست افزونهٔ pytest؛ در Jupyter خود Notebook از قبل حلقه دارد.

بدفهمی رایج: «داخل Async با asyncio.run() ۱ Coroutine را همگام اجرا می‌کنم.» خطای واقعی: RuntimeError: asyncio.run() cannot be called from a running event loop. در Async باید await کنید؛ از یک Thread می‌توانید asyncio.run_coroutine_threadsafe(coro, loop) بزنید. nest_asyncio درون asyncio را تغییر می‌دهد: "This module patches asyncio to allow nested use of asyncio.run and loop.run_until_complete". اما uvloop را پشتیبانی نمی‌کند: "Only event loops from asyncio can be patched"؛ مشکل طراحی را پنهان می‌کند و باید راه‌حل موقت Notebook بماند.

تعریف: asyncio.run(coro, *, debug=None) از 3.7+ و پارامتر loop_factory از 3.12+، حلقه می‌سازد، Coroutine را اجرا می‌کند، Task باقی‌مانده را لغو می‌کند، Async generator و Executor پیش‌فرض را می‌بندد و حلقه را می‌بندد. asyncio.Runner از 3.11+ همین سازوکار را برای چند فراخوانی روی ۱ حلقه می‌دهد. loop.run_until_complete(fut) روش قدیمی سطح پایین است و برای مدیریت دستی حلقه، مثل سرور تست این فصل در Thread خودش، هنوز به کار می‌رود. loop.run_forever() با loop.stop() برای سرور است. asyncio.get_event_loop() رفتار "rather complex behavior" دارد و از 3.14: "Raises a RuntimeError if there is no current event loop". مستندات در Coroutine و Callback، get_running_loop() را ترجیح می‌دهند.

     asyncio.run(main())
1    loop = new_event_loop(); set as current
2    task = loop.create_task(main()); loop.run_until_complete(task)
3    main returns
4    cancel all remaining tasks; run loop until they finish cancelling
5    loop.run_until_complete(loop.shutdown_asyncgens())
6    loop.run_until_complete(loop.shutdown_default_executor())   (3.9+)
7    loop.close()

سناریوی واقعی: فرمان CLI ۳ API ناهمگام را با asyncio.run می‌خواند. Task همگام Celery به Client ناهمگام نیاز دارد؛ asyncio.run برای هر Task یا بهتر از آن Client همگام. فرمان مدیریتی Django کتابخانهٔ Async را صدا می‌زند. در Notebook، await سطح بالا کار می‌کند ولی asyncio.run خطا می‌دهد. Thread با run_coroutine_threadsafe کار را به حلقهٔ اصلی می‌سپارد.

وضعیتابزار
ورودی اسکریپت / CLIasyncio.run(main())
چند اجرا روی یک حلقه، 3.11+with asyncio.Runner() as r: r.run(a()); r.run(b())
حلقهٔ سفارشی uvloopuvloop.run(main()) یا asyncio.run(main(), loop_factory=uvloop.new_event_loop) در 3.12+
داخل Coroutineawait
از Thread دیگر به حلقهٔ فعالasyncio.run_coroutine_threadsafe(coro, loop).result()
حلقه در Thread پس‌زمینهloop.run_until_complete(...) / run_forever() در همان Thread
Jupyter / IPythonawait سطح بالا؛ Kernel حلقه دارد؛ nest_asyncio فقط آخرین راه
کد Sync با یک فراخوانی Asyncanyio.from_thread.run از Worker Thread یا asyncio.run در Thread تازه

اشکال‌زدایی (Debugging): PYTHONASYNCIODEBUG، Debug mode، Callback کند و "coroutine was never awaited" حیاتی ​

به زبان ساده: حالت اشکال‌زدایی (Debug mode) در asyncio خطاهای کلاسیک را می‌سنجد: Callback طولانی، Coroutine بدون await همراه محل ساخته‌شدن، و فراخوانی غیر Thread-safe از Thread دیگر. در توسعه و تست روشنش کنید.

بدفهمی رایج: «چیزی Log نشده، پس چیزی حلقه را نمی‌بندد.» هشدار Callback کند فقط در Debug mode هست؛ time.sleep ۲۰۰ میلی‌ثانیه‌ای داخل Coroutine در حالت معمول هیچ پیامی دربارهٔ کندی نداد؛ stderr آن حالت خط Executing ندارد. پیام "coroutine was never awaited" هم هنگام جمع‌آوری شیء چاپ می‌شود که می‌تواند از محل باگ دور باشد؛ Debug mode محل ساخت را ثبت می‌کند.

تعریف: "There are several ways to enable asyncio debug mode: Setting the PYTHONASYNCIODEBUG environment variable to 1. Using the Python Development Mode. Passing debug=True to asyncio.run(). Calling loop.set_debug()." در Debug mode: "Callbacks taking longer than 100 milliseconds are logged. The loop.slow_callback_duration attribute can be used to set the minimum execution duration in seconds that is considered "slow"". I/O کند Selector ثبت می‌شود و "Many non-threadsafe asyncio APIs (such as loop.call_soon() and loop.call_at() methods) raise an exception if they are called from a wrong thread". مستندات logging.basicConfig(level=logging.DEBUG) و -W default برای ResourceWarning را هم توصیه می‌کنند. پرچم‌های python -I یا -E متغیرهای PYTHON* از جمله PYTHONASYNCIODEBUG را نادیده می‌گیرند؛ این نکته هنگام ساخت تست کشف شد. نسخهٔ 3.14، python -m asyncio ps PID و pstree PID را برای مشاهدهٔ Taskهای Process فعال افزود.

     the same script, two modes (real, tests/test_debug.py, CPython 3.9.6)
1    default:  <string>:8: RuntimeWarning: coroutine 'forgotten' was never awaited
2              Task exception was never retrieved / future: <Task finished name='Task-2' ... exception=ValueError('lost')>
3    PYTHONASYNCIODEBUG=1: the same two, plus
4              Coroutine created at (most recent call last) ... File "<string>", line 8, in main
5              Executing <Task pending name='Task-1' coro=<main() running at <string>:13> ...> took 0.213 seconds
6              source_traceback: Object created at (most recent call last) ...

سناریوی واقعی: جهش تأخیر صدک ۹۹ از json.dumps پاسخ ۲۰ MB داخل async def می‌آید و در تست بار با Debug mode پیدا می‌شود. Task پس‌زمینه هفته‌ها پیش بی‌صدا مرده و پیام Task exception was never retrieved در Log خوانده‌نشده مانده است. await فراموش‌شدهٔ session.commit() باعث ناپدیدشدن نوشتن‌ها شده است. مجموعهٔ تست در CI با PYTHONASYNCIODEBUG=1 جلوی بازگشت باگ را می‌گیرد.

نشانهعلت محتملروش یافتن
coroutine '...' was never awaitedawait جا افتاده یا به‌جای تابع Coroutine داده شدهDebug mode محل "Coroutine created at" را نشان می‌دهد
Task exception was never retrievedشکست Task رهاشدهارجاع نگه دارید و Callback پایان Log کند
Task was destroyed but it is pending!بستن حلقه با Task زنده یا جمع‌آوری Task بی‌ارجاعلغو و await در خاموشی
Executing <Task ...> took 0.213 secondsBlocking یا CPU روی حلقهrepr مربوط به Task نام Coroutine و خط را می‌دهد
کندی همهٔ Endpointها با همحلقه بسته استDebug mode، تأخیر Heartbeat، py-spy dump
... attached to a different loop در tasks.py نسخهٔ 3.9ابزار، Future یا Client روی حلقهٔ دیگر ساخته شده؛ تست یا importداخل حلقهٔ در حال اجرا بسازید
RuntimeError: Non-thread-safe operation invoked on an event loop other than the current onecall_soon از Thread در Debug modecall_soon_threadsafe

اصلاح / روش استفاده: تست و سرور محلی را با PYTHONASYNCIODEBUG=1 یا python -X dev اجرا کنید؛ در تست بار loop.slow_callback_duration را به ۰٫۰۵ کاهش دهید و هر پیام بالا را باگ بدانید.

py
"""Debug mode and the warnings it prints, captured from a child interpreter."""
from __future__ import annotations

import os
import re
import subprocess
import sys
import textwrap

import pytest

SCRIPT = textwrap.dedent(
    """
    import asyncio, time

    async def forgotten():
        return 1

    async def main():
        forgotten()                 # missing await
        time.sleep(0.2)             # blocks the loop for 200 ms
        async def boom():
            raise ValueError("lost")
        t = asyncio.ensure_future(boom())
        await asyncio.sleep(0.01)
        del t                       # exception never retrieved

    asyncio.run(main())
    """
)


def run_child(env_extra: dict[str, str]) -> str:
    env = {**os.environ, "PYTHONDONTWRITEBYTECODE": "1", **env_extra}
    if "PYTHONASYNCIODEBUG" not in env_extra:
        env.pop("PYTHONASYNCIODEBUG", None)
    # No -I/-E here: those flags make the child ignore PYTHON* variables, debug mode included.
    proc = subprocess.run([sys.executable, "-c", SCRIPT], capture_output=True, text=True, env=env, timeout=30)
    return proc.stderr


def test_never_awaited_warning_without_debug() -> None:
    err = run_child({})
    print("\n--- default mode stderr ---\n" + err)
    assert "RuntimeWarning: coroutine 'forgotten' was never awaited" in err
    assert "Task exception was never retrieved" in err
    assert "Executing" not in err  # no slow-callback report outside debug mode


@pytest.mark.parametrize("env", [{"PYTHONASYNCIODEBUG": "1"}])
def test_debug_mode_reports_slow_callbacks(env: dict[str, str]) -> None:
    err = run_child(env)
    print("\n--- PYTHONASYNCIODEBUG=1 stderr ---\n" + err)
    assert re.search(r"Executing <Task .* took \d+\.\d+ seconds", err)  # slow callback (> 100 ms)
    assert "Coroutine created at" in err or "was never awaited" in err

Client ناهمگام HTTP: httpx.AsyncClient و محدودیت اتصال (Connection limits) حیاتی ​

به زبان ساده: httpx.AsyncClient همتای ناهمگام httpx.Client است؛ همان API با await. برای هر Process یکی بسازید و دوباره استفاده کنید. مجموعهٔ اتصال (Connection pool) دارد، پس درخواست‌های یک Host اتصال TCP و TLS را دوباره مصرف می‌کنند.

بدفهمی رایج: «داخل هر درخواست async with httpx.AsyncClient() as c: طبیعی است.» این کار هر بار Pool و Handshake تازهٔ TCP/TLS می‌سازد و سقفی بین درخواست‌ها ندارد. مستندات httpx: "If you do anything more than experimentation, one-off scripts, or prototypes, then you should use a Client instance" چون "a Client instance uses HTTP connection pooling". مانند برنامهٔ بعد، ۱ بار در Lifespan باز کنید. همچنین «gather روی ۱۰٬۰۰۰ URL خوب است چون httpx سقف اتصال دارد» غلط است؛ سقف اتصال پیش‌فرض ۱۰۰ است، اما هنوز ۱۰٬۰۰۰ Task می‌سازید و در صف Pool منتظر می‌مانید و ممکن است Pool timeout بگیرید. تعداد Task را هم محدود کنید.

تعریف: مستندات Limits در httpx: "max_keepalive_connections, number of allowable keep-alive connections, or None to always allow. (Defaults 20) max_connections, maximum number of allowable connections, or None for no limits. (Default 100) keepalive_expiry … (Default 5)". دربارهٔ Timeout: "The default behavior is to raise a TimeoutException after 5 seconds of network inactivity"؛ با httpx.Timeout برای connect، read، write و pool جدا تنظیم می‌شود. httpx.AsyncClient(transport=httpx.ASGITransport(app=app)) برنامهٔ ASGI را در همان Process صدا می‌زند و در تست‌ها استفاده شده است. trust_env=False متغیرهای Proxy محیط را نادیده می‌گیرد: "Environment variables are used by default. To ignore environment variables, trust_env has to be set False". قطعه‌کدها این را تنظیم می‌کنند تا Proxy توسعه‌دهنده اندازه‌گیری را عوض نکند. API مربوط به asyncio در Redis Client طبق مستندات redis-py، import redis.asyncio as redis است.

     20 x GET /delay/100 (real, app/fanout.py, the measurement in the Lab)
1    sync sequential (httpx.Client)           2.072 s   20 x 100 ms, one after another
2    sync + ThreadPoolExecutor(20)            0.133 s   20 threads, shared thread-safe Client
3    async gather (httpx.AsyncClient)         0.136 s   20 tasks, one thread
4    async gather + Semaphore(5)              0.439 s   4 waves of 5
5    sync client inside async def + gather    2.068 s   no await -> no overlap

سناریوی واقعی: Backend رابط کاربری یا BFF ۶ سرویس داخلی را برای هر صفحه می‌خواند؛ ارسال‌کنندهٔ Webhook هزاران مشترک دارد؛ تجمیع‌کنندهٔ قیمت ۵۰ تأمین‌کننده را Poll می‌کند؛ دروازهٔ LLM با client.stream(...) و aiter_bytes() پاسخ را تدریجی می‌فرستد. Retry، مدارشکن (Circuit breaker) و Cache این فراخوانی‌ها در کار پس‌زمینه، Cache و API خارجی هستند.

تنظیمپیش‌فرضزمان تغییر
Limits(max_connections=...)100بالادست کمتر اجازه می‌دهد یا تعداد Worker × 100 زیاد است
Limits(max_keepalive_connections=...)20Fan-out پایدار و زیاد به یک Host
Limits(keepalive_expiry=...)5 sTimeout بیکاری Load balancer کوتاه‌تر است
Timeout(5.0)5 s برای هر مرحلههمیشه برای هر بالادست صریح تنظیم کنید
Timeout(pool=...)5 sTaskهای زیادی منتظر اتصال Pool هستند
یک Client برای هر Processمسئولیت شماهمیشه؛ ساخت در Lifespan و بستن هنگام خاموشی

اصلاح / روش استفاده: lifespan در app/after.py الگوست: یک AsyncClient با Limits و Timeout صریح روی app.state، یک Semaphore حداکثر به‌اندازهٔ max_connections و سررسید در سطح asyncio برای هر فراخوانی.

استفادهٔ FastAPI، Starlette و Uvicorn از حلقه (Event loop) حیاتی ​

به زبان ساده: Uvicorn برای هر Worker process ۱ حلقهٔ رویداد (Event loop) آغاز می‌کند و هر درخواست آن Worker را به‌شکل Coroutine روی آن اجرا می‌کند. FastAPI، Route با async def را روی همان حلقه await می‌کند؛ Route با def را در Worker Thread اجرا می‌کند تا Blocking حلقه را متوقف نکند. Starlette و FastAPI این کار را با AnyIO انجام می‌دهند.

بدفهمی رایج: «Route با def سبک قدیمی و کند است.» برای کتابخانهٔ Blocking انتخاب درست است. مستندات FastAPI دربارهٔ عملیات مسیر (Path operation) با def می‌گویند: "is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server)". اشتباه اصلی کد Blocking در async def است. اندازه‌گیری اولیهٔ ۵ درخواست ۲۰۰ میلی‌ثانیه‌ای با زمان ۱٫۰۵ در برابر ۰٫۲۱ ثانیه در مبانی FastAPI است؛ قبل/بعد این صفحه آن را برای Route دارای Fan-out نشان می‌دهد.

تعریف: گزینهٔ --loop در Uvicorn: "Set the event loop implementation. The uvloop implementation provides greater performance, but is not compatible with Windows or PyPy … Options: 'auto', 'asyncio', 'uvloop' … Default: 'auto'". مستندات جاری zuvloop را هم برای CPython 3.14+ فهرست می‌کنند که در نسخهٔ ثابت 0.39.0 نیست. خروجی واقعی 0.39.0: --loop auto: uvloop.Loop tokens=40 و --loop asyncio: asyncio.unix_events._UnixSelectorEventLoop tokens=40. در Starlette، run_in_threadpool(func, *args) همان await anyio.to_thread.run_sync(func) است: "The default thread pool size is only 40 tokens. This means that only 40 threads can run at the same time". با anyio.to_thread.current_default_thread_limiter().total_tokens تغییر می‌کند. Dependency همگام، Dependency همگام دارای yield و پاسخ فایل همین Pool را مصرف می‌کنند.

     one Uvicorn worker, three requests (real thread names from test_before_after.py)
1    loop thread    GET /dashboard/ana (async def): awaits 5 upstream calls via AsyncClient
2    loop thread    GET /health (async def): answered while /dashboard waits -> 0.002 s
3    AnyIO worker   GET /report (def): time.sleep(0.05) in "AnyIO worker thread"
4    AnyIO worker   GET /legacy (async def) -> await run_in_threadpool(...) -> "AnyIO worker thread"
5    loop thread    /dashboard resumes, to_thread(render_chart) -> default executor -> returns

سناریوی واقعی: بخشی از Routeها SQLAlchemy همگام با def دارند و بخشی httpx ناهمگام با async def. درخواست هم‌زمان شمارهٔ ۴۱ def منتظر می‌ماند چون ۴۰ توکن در پایگاه دادهٔ کند مشغول‌اند. تیم برای یافتن مشکل ویژهٔ uvloop، --loop asyncio می‌گذارد. ماشین توسعهٔ Windows بدون uvloop کار می‌کند.

Route / فراخوانیمحل اجراسقف هم‌روندیاگر Blocking باشد حلقه را می‌بندد؟
Route با async defEvent loopداخلی ندارد؛ Uvicorn --limit-concurrencyبله
Route با defAnyIO Worker Thread40 توکن مشترکنه
Dependency با async defEvent loopنداردبله
Dependency با def، شامل yieldAnyIO Worker Thread40 توکننه
await run_in_threadpool(f)AnyIO Worker Thread40 توکننه
await asyncio.to_thread(f)Executor پیش‌فرض asynciomin(32, cpu + 4)نه
BackgroundTasks.add_task(def_fn)AnyIO Worker Thread پس از پاسخ40 توکننه
StreamingResponse(sync_iterator)iterate_in_threadpool40 توکننه

اصلاح / روش استفاده: وقتی همهٔ کارهای منتظر داخل تابع await می‌شوند async def؛ در غیر این صورت def. محدودکنندهٔ AnyIO را فقط پس از اندازه‌گیری در Lifespan افزایش دهید؛ هر توکن می‌تواند ۱ Thread و معمولاً یک اتصال پایگاه داده باشد. تنظیم Worker Process، --limit-concurrency و خاموشی آرام در FastAPI در Production است.

تست کد ناهمگام (Async testing): pytest-asyncio و افزونهٔ pytest در AnyIO مهم ​

به زبان ساده: pytest به‌تنهایی اجرای تست async def را بلد نیست. افزونه برای هر تست یا Module/Session یک Event loop می‌سازد و Coroutine را روی آن اجرا می‌کند.

بدفهمی رایج: «pytest تست Async را مثل بقیه اجرا می‌کند.» بدون افزونه اجرا نمی‌شود؛ pytest 8.4.2 با افزونه‌های خاموش واقعاً خطای async def functions are not natively supported. و "You need to install a suitable plugin for your async framework" داده است؛ runs/pytest-no-plugin.txt. در حالت سخت‌گیرانه (Strict mode) pytest-asyncio، تست async def بدون Marker هم به افزونه سپرده نمی‌شود. همهٔ تست‌های Async را علامت بزنید یا حالت خودکار (Auto mode) تنظیم کنید؛ نتیجه‌ای را اطمینان‌سنجی (Assert) کنید که فقط کد awaitشده تولید می‌کند.

تعریف: pytest-asyncio "provides two modes for test discovery, strict and auto. … In strict mode pytest-asyncio will only run tests that have the asyncio marker". تنظیم asyncio_mode = "auto" همهٔ تست‌های async def را asyncio حساب می‌کند. @pytest.mark.asyncio(loop_scope="module") حلقه را بین تست‌ها شریک می‌کند و asyncio_default_fixture_loop_scope حوزهٔ حلقهٔ Fixture ناهمگام را تعیین می‌کند. نسخهٔ استفاده‌شده 1.2.0، آخرین پشتیبان Python 3.9 است؛ 1.3.0 حداقل 3.10 می‌خواهد. AnyIO افزونهٔ داخلی با @pytest.mark.anyio و Fixture به‌نام anyio_backend دارد که "asyncio" یا "trio" است. هشدار مستندات: Auto mode آن "does not work if pytest-asyncio is installed and configured to use its own auto mode, as it will conflict with the AnyIO plugin". پس پروژه Strict mode دارد و هر تست صریح علامت می‌خورد. صفحهٔ «Async Tests» در FastAPI از @pytest.mark.anyio با httpx.AsyncClient(transport=ASGITransport(app=app)) استفاده می‌کند.

     tests/ in this chapter (real: 43 passed, 2 skipped in 10.17 s)
1    @pytest.mark.asyncio  -> pytest-asyncio creates a loop for the test, runs it, closes it
2    @pytest.mark.anyio    -> AnyIO plugin runs it on the backend from anyio_backend ("asyncio")
3    plain def tests       -> run sync; they call asyncio.run() themselves where needed
4    @needs_311            -> skipif(sys.version_info < (3, 11)): TaskGroup, asyncio.timeout
5    session fixture       -> the local upstream server in its own thread, shared by all tests

سناریوی واقعی: Routeهای Async در FastAPI با httpx.AsyncClient و ASGITransport تست می‌شوند؛ Lifespan را با app.router.lifespan_context(app) دستی وارد می‌شوید چون ASGITransport آن را اجرا نمی‌کند. Repository ناهمگام با SQLite و aiosqlite تست می‌شود. کتابخانه روی asyncio و Trio با افزونهٔ AnyIO تست می‌شود. تست ناپایدار از asyncio.Lock() سطح ماژول می‌آید که به حلقهٔ دیگری وابسته شده است.

ابزارMarker / تنظیمحوزهٔ حلقهنکته
pytest-asyncio سخت‌گیرانه@pytest.mark.asyncioپیش‌فرض تابع؛ loop_scope=حالت پیش‌فرض
pytest-asyncio خودکارasyncio_mode = "auto"همانتداخل با Auto mode در AnyIO
افزونهٔ AnyIO@pytest.mark.anyio، Fixture به‌نام anyio_backendهر تستasyncio و Trio؛ در مستندات FastAPI
TestClient در Starletteتست همگامحلقهٔ مستقل در Thread با PortalLifespan را در with اجرا می‌کند
httpx.ASGITransportتست Asyncحلقهٔ خود تستLifespan ندارد؛ دستی وارد شوید
unittest.IsolatedAsyncioTestCaseکتابخانهٔ استانداردهر تستبدون افزونه

اصلاح / روش استفاده: pyproject.toml و تست‌های بالا الگو هستند. جزئیات Fixture، Override و پایگاه داده در تست FastAPI است.

خاموشی آرام (Graceful shutdown) وظیفه‌ها مهم ​

به زبان ساده: وقتی Process فرمان توقف می‌گیرد، مثلاً SIGTERM از Kubernetes یا Ctrl+C، درخواست‌های در جریان باید تمام شوند؛ Taskهای پس‌زمینه مهلت کوتاه بگیرند و باقی‌مانده لغو و await شوند تا finally اتصال‌ها را ببندد، سپس Process خارج شود. این خاموشی آرام (Graceful shutdown) است.

بدفهمی رایج: «Uvicorn خاموشی را انجام می‌دهد، Taskهای من مشکلی ندارند.» Uvicorn پذیرش اتصال را متوقف می‌کند، با سقف --timeout-graceful-shutdown منتظر درخواست باز می‌ماند و سپس بخش خاموشی Lifespan را اجرا می‌کند. Task ساختهٔ خودتان مسئولیت خودتان است. اگر Lifespan لغو و await نکند، همراه حلقه نابود می‌شود: Task was destroyed but it is pending!؛ پاک‌سازی‌اش اجرا نمی‌شود.

تعریف: هر Task پس‌زمینه در مالک نگه‌داری می‌شود: Set، TaskGroup یا Task group در AnyIO. در Lifespan پس از yield تا سررسید با asyncio.wait(tasks, timeout=...) صبر کنید، ناتمام‌ها را لغو کنید و با await asyncio.gather(*pending, return_exceptions=True) پایان لغو را منتظر بمانید. asyncio.run پیش از بستن حلقه همین را به‌عنوان آخرین چاره برای همهٔ Taskهای باقی‌مانده انجام می‌دهد. Queue.shutdown() در 3.13 تولیدکننده و مصرف‌کنندهٔ صف را تمیز متوقف می‌کند.

     SIGTERM to a Uvicorn worker running app/after.py (lifespan shutdown, real in test_after_shutdown_drains_background_tasks)
1    Uvicorn stops accepting; waits for in-flight requests (--timeout-graceful-shutdown)
2    lifespan resumes after `yield`
3    background.drain(timeout=2.0): wait for audit tasks -> done within the deadline
4    pending tasks (if any) cancelled and awaited -> their finally blocks run
5    AsyncClient.__aexit__ closes pooled connections
6    process exits; app.state.cancelled_on_shutdown == 0, audit_log == ["bo"]

سناریوی واقعی: Kubernetes پس از SIGTERM به‌اندازهٔ terminationGracePeriodSeconds منتظر می‌ماند و بعد SIGKILL می‌فرستد. حلقهٔ مصرف باید پیام جدید نگیرد ولی پیام جاری را تمام و Ack کند. سرور WebSocket اتصال Client را با کد «going away» می‌بندد. تازه‌کنندهٔ دوره‌ای Cache باید بدون کلید نیمه‌نوشته متوقف شود.

قدممالکمحدودیت
توقف پذیرش کار تازهUvicorn / حلقهٔ مصرف با Eventفوری
پایان درخواست در جریانUvicorn--timeout-graceful-shutdown
تخلیهٔ Task پس‌زمینهLifespan شماچند ثانیه
لغو باقی‌مانده و await آنLifespan شماتا پایان finallyها
بستن Client و Poolasync with در Lifespanفوری
کشتن اجباریOrchestrator با SIGKILLمهلت خاتمه

اصلاح / روش استفاده: BackgroundTasks.drain() در app/tasks.py و Lifespan در app/after.py را ببینید. جمع زمان باید از مهلت Orchestrator کوتاه‌تر باشد؛ تنظیم استقرار در FastAPI در Production است.

پایگاه داده در کد Async: Driver همگام و ناهمگام، یک Session برای هر Task تکمیلی ​

به زبان ساده: فراخوانی پایگاه داده I/O شبکه است، پس در کد Async باید با Driver ناهمگام await شود. Driver همگام در async def هر Query را روی حلقه مسدود می‌کند؛ رایج‌ترین راه ازدست‌دادن هم‌روندی FastAPI همین است.

بدفهمی رایج: «Driver ناهمگام اجازه می‌دهد یک Session چند Query موازی اجرا کند.» یک اتصال (Connection) و نشست (Session) در SQLAlchemy در هر لحظه یک Statement را انجام می‌دهد؛ هم‌روندی از چند Connection می‌آید. SQLAlchemy: "The AsyncSession is not safe for use in concurrent tasks." هر درخواست یا Task ۱ Session می‌خواهد و Pool باید متناسب سقف هم‌روندی باشد.

تعریف: Driverهای Sync شامل psycopg2، pymysql، sqlite3 و Session همگام SQLAlchemy هستند. Asyncها شامل asyncpg، حالت Async در psycopg 3، aiomysql/asyncmy و aiosqlite هستند. افزونهٔ asyncio در SQLAlchemy 2 با create_async_engine و AsyncSession روی آن‌ها اجرا می‌شود و برای پیش‌برد درون ORM از greenlet استفاده می‌کند؛ SQLModel و Alembic بالای آن قرار دارند. با Driver همگام، Route را def نگه دارید تا FastAPI آن را در Thread اجرا کند یا با to_thread صدا بزنید؛ Pool را حداقل به‌اندازهٔ Threadهای مصرف‌کننده بگیرید. جزئیات ORM در SQLAlchemy 2 و SQLModel و Migration در Alembic است.

     three concurrent requests, async driver, pool size 2
1    task A: acquire conn 1 -> await SELECT ...        (loop free)
2    task B: acquire conn 2 -> await SELECT ...        (loop free)
3    task C: await pool.acquire()  -> waits for a free connection (pool timeout applies)
4    A's result arrives -> A releases conn 1 -> C acquires it
     sync driver in async def instead: A's query holds the loop; B and C cannot even start

سناریوی واقعی: FastAPI با Routeهای async def و psycopg2 هر Query را به مانع همهٔ درخواست‌ها تبدیل می‌کند. مهاجرت به asyncpg به expire_on_commit=False و Eager loading صریح هم نیاز دارد؛ Lazy load در کد Async در SQLAlchemy خطا می‌دهد. اسکریپت asyncio.gather با ۱ AsyncSession مشترک خطای وضعیت Session می‌گیرد. Pool ۵ اتصالی پشت ۴۰ توکن Thread گلوگاه می‌شود.

Stackشکل Routeحلقه را می‌بندد؟محل آموزش
SQLAlchemy Session با psycopg2 / sqlite3defنه؛ Thread poolSQLAlchemy 2 و SQLModel
SQLAlchemy Session در async defasync defبله؛ باگهمین صفحه
AsyncSession با asyncpg / aiosqliteasync defنهSQLAlchemy 2 و SQLModel
asyncpg مستقیمasync defنهمستندات asyncpg
Motor / Beanie برای MongoDBasync defنهMongoDB با FastAPI
redis.asyncioasync defنهکار پس‌زمینه و Cache

اصلاح / روش استفاده: برای هر Route ۱ سبک انتخاب کنید و سرتاسر همان را نگه دارید. SQL بالا در query_orders در هر ۲ یکسان ارسال می‌شود؛ فقط انتظار فرق دارد.

سازوکار (Mechanics) ​

Task چگونه Coroutine را پیش می‌برد؟ مهم ​

کوروتین (Coroutine) شیئی شبیه Generator با send() و throw() است. وظیفه (Task)، coro.send(None) را صدا می‌زند؛ Coroutine تا جایی اجرا می‌شود که داخلی‌ترین await به چیزی ناآماده برسد و یک Future را تا بالای زنجیره yield کند. Task با add_done_callback متد بیدارشدنش را روی Future ثبت می‌کند و کنترل را به حلقه پس می‌دهد. وقتی Future نتیجه گرفت، مثلاً سوکت خواندنی شد، Timer رسید یا Thread تمام شد، Callback با call_soon قدم بعدی Task را زمان‌بندی می‌کند و send(None) از محل توقف ادامه می‌دهد. لغو در قدم بعدی با coro.throw(CancelledError) است. هیچ‌کدام پیش‌دستانه نیست؛ نقطهٔ جابه‌جایی yield خروجی از send() است که فقط هنگام await روی Future معلق یا yield خالی رخ می‌دهد. asyncio.sleep(0) همین yield خالی را دارد و tasks.py وقتی result is None باشد قدم بعدی را زمان‌بندی می‌کند. await روی Coroutine بدون تعلیق یا Future تمام‌شده در همان قدم ادامه می‌یابد. خروجی واقعی runs/probe_await_yield-output.txt: ['after await instant()', 'after await done Future', 'child', 'after await asyncio.sleep(0)']. حلقه‌ای از این awaitها درست مثل حلقهٔ CPU بقیهٔ Taskها را گرسنه نگه می‌دارد.

     Task.__step (CPython asyncio/tasks.py), one await of a socket read
1    result = coro.send(None)              # runs your code up to the next real suspension
2    result is a Future with _asyncio_future_blocking set   # e.g. the Future of a pending sock_recv
3    result.add_done_callback(self.__wakeup)
4    return                                # back to the loop; other handles run
5    ... selector: socket readable -> reader callback -> fut.set_result(data)
6    fut's done callbacks are scheduled: loop.call_soon(self.__wakeup, fut)
7    __wakeup -> __step -> coro.send(None) -> the await expression returns data
8    on task.cancel(): next __step does coro.throw(CancelledError) instead of send
رویدادعاملAPI زیرین
create_task(coro)حلقهloop.call_soon(task.__step)
await asyncio.sleep(d)Heap زمان‌سنج حلقهloop.call_later(d, futures._set_result_unless_cancelled, future, result)
await reader.read()Selectorloop.add_reader(fd, callback)
await to_thread(f)Thread در Executorloop.run_in_executor + call_soon_threadsafe
task.cancel()Taskپرچم می‌گذارد؛ قدم بعد CancelledError پرتاب می‌کند
پایان TaskCallbackهای FutureTaskهای منتظر بیدار می‌شوند

متن دقیق خطا، هشدار و Log حیاتی ​

همهٔ خط‌های زیر خروجی واقعی اجرای قطعه‌کد یا Probeهای ذخیره‌شده در pipeline/sources/async-python-asyncio/runs/ هستند؛ CPython 3.9.6، anyio 4.12.1، Uvicorn 0.39.0 و pytest 8.4.2.

محرکخروجی
Coroutine بدون awaitRuntimeWarning: coroutine 'forgotten' was never awaited + RuntimeWarning: Enable tracemalloc to get the object allocation traceback
همان در Debug modeافزودن Coroutine created at (most recent call last) با پشته
Task شکست‌خورده بدون awaitTask exception was never retrieved / future: <Task finished name='Task-2' coro=<main.<locals>.boom() done, ...> exception=ValueError('lost')>
بستن حلقه با Task معلقTask was destroyed but it is pending! / task: <Task pending name='Task-6' coro=<forever() done, ...> wait_for=<Future pending ...>>
Callback کند در Debug modeExecuting <Task pending name='Task-1' coro=<main() running at <string>:13> ...> took 0.213 seconds
asyncio.run در حلقهٔ فعالRuntimeError: asyncio.run() cannot be called from a running event loop
دوبار await یک CoroutineRuntimeError: cannot reuse already awaited coroutine
asyncio.TaskGroup در 3.9AttributeError: module 'asyncio' has no attribute 'TaskGroup'
Coroutine خام به wait() در 3.9DeprecationWarning: The explicit passing of coroutine objects to asyncio.wait() is deprecated since Python 3.8, and scheduled for removal in Python 3.11.
put_nowait در صف پرasyncio.QueueFull
asyncio.TimeoutError is TimeoutError در 3.9False؛ از 3.11 نام مستعار
کلاس پایهٔ CancelledError در 3.9BaseException
حلقهٔ پیش‌فرض macOS_UnixSelectorEventLoop، slow_callback_duration: 0.1
Uvicorn --loop auto / asyncio / uvloopuvloop.Loop / asyncio.unix_events._UnixSelectorEventLoop / uvloop.Loop؛ AnyIO در هرکدام tokens=40
نام Thread برای Route با def / run_in_threadpoolAnyIO worker thread
Executor پیش‌فرض روی 12 CPUmax_workers=16
تست Async بدون Marker و افزونه، pytest 8.4.2async def functions are not natively supported.
گروه AnyIO با فرزند شکست‌خوردهExceptionGroup از Backport بستهٔ exceptiongroup روی 3.9، شامل ValueError فرزند

ماتریس نسخه‌ها: چه چیزی کجا قابل استفاده است؟ مهم ​

ویژگی3.93.103.113.123.133.143.15
asyncio.run، create_task، gather، wait_for، Queueبلهبلهبلهبلهبلهبلهبله
asyncio.to_threadبله؛ تازهبلهبلهبلهبلهبلهبله
پارامتر loop= در API سطح بالامنسوخحذفحذفحذفحذفحذفحذف
TaskGroup، timeout()، Runner، Barrier، except*نهنهبلهبلهبلهبلهبله؛ با tg.cancel()
asyncio.TimeoutError is TimeoutErrorنهنهبلهبلهبلهبلهبله
Coroutine خام در wait()هشدارهشدارخطاخطاخطاخطاخطا
Eager task factory و run(loop_factory=)نهنهنهبلهبلهبلهبله
Queue.shutdown و async for روی as_completedنهنهنهنهبلهبلهبله
ساخت Free-threadedنهنهنهنهآزمایشیپشتیبانی‌شده، اختیاریپشتیبانی‌شده، اختیاری
python -m asyncio ps / pstreeنهنهنهنهنهبلهبله
سیستم Policyبلهبلهبلهبلهبلهمنسوخ؛ حذف در 3.16منسوخ؛ حذف در 3.16
اندازهٔ پیش‌فرض ThreadPoolExecutormin(32, cpu_count + 4)همانهمانهمانprocess_cpu_count + 4 با سقف 32همانهمان

حل مسائل رایج (Solving the classic problems) ​

باگنشانهاصلاحهزینه
Client همگام HTTP در Route ناهمگامکندی همهٔ Endpointها هنگام تأخیر بالادست؛ /health واقعی 0.554 shttpx.AsyncClient از Lifespan یا Route با defکم
time.sleep در Coroutine حلقه را می‌بنددفاصلهٔ Heartbeat برابر 0.211 sawait asyncio.sleepندارد
Driver همگام DB در async defتوان عملیاتی یک درخواست در هر لحظهDriver Async یا Route با def و Poolمتوسط
gather نامحدود روی فهرست بزرگاتمام سوکت، 429 بالادست، Pool timeoutSemaphore یا Worker pool روی Queue محدودکم
create_task و رهاکردنکار گم‌شده، Task exception was never retrievedSet قابل پیگیری / TaskGroup؛ صف برای کار پایدارکم
بلعیدن CancelledErrorگیرکردن خاموشی و عمل‌نکردن Timeoutپرتاب دوباره پس از پاک‌سازیندارد
نبود Timeout خروجیانباشت درخواست هنگام اختلالTimeout در Client و wait_for / timeout()ندارد
شکست سریع gather با ادامهٔ هم‌گروهیکار بیهوده و اثر جانبی پس از خطاTaskGroup / Task group در AnyIOکم
CPU روی حلقهجهش تأخیر، Debug "took 0.4 seconds"ProcessPoolExecutor یا صف کارمتوسط
وضعیت درخواست در Thread-localشناسهٔ درخواست اشتباه در LogContextVarکم
خواندن-await-نوشتن بی‌قفلبه‌روزرسانی گم‌شده؛ 50 → 1 واقعیasyncio.Lock یا SQL اتمیکم
Client برای هر درخواستHandshake جدید TLS در هر بار و نبود سقف سراسرییک Client برای هر Processکم
ابزار هماهنگی ساخته‌شده در import"attached to a different loop" در تستساخت در Lifespan / Fixtureکم
Task زنده هنگام خاموشیTask was destroyed but it is pending!تخلیه، لغو و await در Lifespanکم

آزاد نگه‌داشتن حلقهٔ رویداد (Event loop) ​

برنامهٔ قبل ۳ راه بسته‌شدن حلقه را نشان می‌دهد: Client همگام، time.sleep و رندر Blocking. برنامهٔ بعد هر ۳ را با Client ناهمگام، await asyncio.sleep برای تأخیر و to_thread برای مرحلهٔ فاقد همتای Async حذف می‌کند. با ۲ Probe ارزان قطعه‌کدها ثابت کنید: Task ضربان که بدترین فاصله‌اش باید نزدیک دوره‌اش بماند، و تست «ارسال /health حین اجرای Route کند». در محیط عملیاتی یک Canary با Debug mode اجرا کنید یا تأخیر حلقه را با همان Heartbeat به‌عنوان Metric بسنجید.

پخش محدود کار (Bounded fan-out) همراه مهلت ​

gather روی فهرست فقط برای فهرست کوچک با اندازهٔ معلوم مناسب است. برای اندازهٔ تعیین‌شده با ورودی، دور هر فراخوانی Semaphore بگذارید؛ async_bounded و fetch_section در قطعه‌کد همین کار را می‌کنند. سقف آن از max_connections بیشتر نباشد؛ هر فراخوانی سررسید و کل عملیات بودجه داشته باشد. ۲۰ فراخوانی با Semaphore(5) در ۰٫۴۳۹ ثانیه و ۴ موج انجام شدند؛ این بهای محافظت از بالادست است. با TaskGroup در 3.11+ شکست یکی بقیه را هم لغو می‌کند.

هیچ Taskی گم نشود ​

نتیجهٔ هر create_task باید مالک داشته باشد: برای عمر یک بلوک TaskGroup، برای عمر Process یک Set قابل پیگیری مانند BackgroundTasks قطعه‌کد و برای بقای پس از Crash صف کار. مالک شکست را Log می‌کند و در Lifespan تخلیه می‌شود.

لغوی که کار می‌کند (Cancellation) ​

پاک‌سازی در finally یا async with، پرتاب دوبارهٔ CancelledError و shield فقط برای عملیات داخلی دارای ارجاع نگه‌داشته‌شده. حلقهٔ طولانی CPU که باید قابل لغو باشد به await asyncio.sleep(0) نیاز دارد یا باید به Process برود. تست کنید؛ test_cancel_runs_finally_and_propagates در قطعه‌کد حداقل قرارداد است.

انتخاب (Choosing) ​

وضعیتابزارتکنیک تکمیلیدلیل
فراخوانی فراوان شبکه با کتابخانهٔ AsyncTaskهای asyncioSemaphore و Timeoutکم‌هزینه‌ترین هم‌روندی برای هر انتظار
همهٔ نتیجه‌ها، شکست سریع و لغو بقیهTaskGroup از 3.11+ / AnyIOasyncio.timeout پیرامونیStructured concurrency
شکست جزئی پذیرفتنیgather(return_exceptions=True)Log هر شکستمنبع خراب نباید کل صفحه را خراب کند
اولین پاسخ برنده استwait(FIRST_COMPLETED)لغو بازنده‌هاHedged request
ارسال نتیجه به‌محض رسیدنas_completedلغو هنگام خروج زودهنگامکاهش زمان اولین نتیجه
کتابخانه فقط Sync داردto_thread / Route با defExecutor مستقل برای وابستگی کندآزادماندن حلقه
CPU از 10 ms تا چند ثانیهProcessPoolExecutor با run_in_executorSemaphore روی ارسال کاراستفاده از هسته‌ها و حلقهٔ آزاد
CPU طولانی‌تر یا نیاز به بقای Restartصف Celery، arq، RQ، Dramatiqکار بی‌اثر در تکرار (Idempotent)پایداری و Retry
تولیدکننده سریع‌تر از مصرف‌کنندهQueue محدودسیاست رد یا حذفBack-pressure
وضعیت هر درخواست در پشتهٔ فراخوانیContextVarreset در finallyدرستی زیر هم‌روندی
اجرای asyncio و Trio یا Structured concurrency روی 3.9/3.10AnyIO@pytest.mark.anyioیک API و Cancel scope
برنامهٔ Sync با یک فراخوانی Asyncasyncio.runنداردساده‌ترین پل
Notebookawait سطح بالاnest_asyncio فقط در اجبارحلقه از قبل فعال است

چه وقت asyncio، Thread، Process یا Go؟ ​

نیازasyncioThread در CPython پیش‌فرضProcessGo
10,000 اتصال بیکار WebSocket یا SSEبهترینگرانبسیار گرانبهترین
Fan-out به 20 فراخوانی HTTP0.136 s واقعی0.133 s واقعیبیش‌ازحد سنگینGoroutine
زیست‌بوم کتابخانهباید Async باشدهر کتابخانههر کتابخانهکتابخانهٔ Go
CPU موازینداردبرای Python خالص ندارد؛ GILبلهبله
ایمنی فراخوانی Blockingیک فراخوانی همه را نگه می‌داردجدا برای هر Threadجدا برای هر ProcessBlocking طبیعی است
وضعیت مشترکبین awaitها امنقفل همه‌جااشتراک ندارد؛ IPCChannel / Mutex
لغوCancelledError و Scopeفقط پرچم مشارکتیکشتن Processcontext.Context
اشکال‌زداییDebug mode و مشاهدهٔ Taskپشتهٔ هر Threadبرای هر ProcessRace detector و pprof

برای ۲۰ فراخوانی، زمان Thread و asyncio یکسان بود. برتری asyncio وقتی است که تعداد انتظار هم‌زمان به هزاران برسد و حافظه و سقف Thread مهم شود، یا Timeout و Cancellation قابل ترکیب بخواهید. ستون Go در نگاه Go باز می‌شود.

در معماری: از ۱ پردازه (Process) تا سیستم توزیع‌شده (In architecture) ​

یکپارچه (Monolith): ۱ Process و ۱ پایگاه داده ​

یک برنامهٔ FastAPI زیر یک Worker در Uvicorn، یک Event loop، یک httpx.AsyncClient، یک Pool ناهمگام پایگاه داده، یک محدودکنندهٔ Thread در AnyIO و یک Set قابل پیگیری Task پس‌زمینه دارد؛ همه در Lifespan ساخته می‌شوند. قواعد این صفحه داخل همان Process اعمال می‌شوند: نبود Blocking روی حلقه، Fan-out محدود، Timeout هر فراخوانی و تخلیهٔ Taskها هنگام خاموشی. مثال فروشگاه: صفحهٔ محصول قیمت، موجودی و نظر را هم‌روند await می‌کند؛ ۳ Query روی ۳ اتصال Pool، با تأخیر حدود ۱ رفت‌وبرگشت به‌جای ۳. PDF صورتحساب در Process pool و ایمیل تأیید سفارش در Task پس‌زمینهٔ قابل پیگیری اجرا می‌شوند.

یکپارچهٔ ماژولار (Modular monolith) و چند پایگاه داده ​

هنوز هر Process ۱ حلقه دارد اما ماژول‌هایی که همدیگر را نمی‌شناسند آن را شریک‌اند. منابع مشترک نقطهٔ رقابت می‌شوند: Executor پیش‌فرض، اینجا ۱۶ Thread، میان همهٔ to_threadهای ماژول‌ها مشترک است؛ محدودکنندهٔ AnyIO با ۴۰ توکن میان همهٔ Routeهای def و Dependencyهای Sync؛ Pool مربوط به HTTP هم میان بالادست‌ها. به هر وابستگی کند Executor و Client با سقف مستقل بدهید تا SDK همگام کند ماژول گزارش، Checkout را گرسنه نگذارد. برای PostgreSQL، Redis و Index جست‌وجو هرکدام Client ناهمگام با اندازهٔ Pool مستقل بگذارید. مجموع مصرفشان ضربدر Workerها باید از سقف اتصال هر سرور کمتر بماند.

ریزخدمت‌ها (Microservices) ​

هر عبور شبکه awaitی است که می‌تواند کند یا ناموفق شود؛ ابزار درون Process حالا ابزار سیستم توزیع‌شده می‌شود. Timeout هر فراخوانی از بودجهٔ فراخواننده کوتاه‌تر باشد؛ انتقال سررسید (Deadline propagation) مثلاً با Header بودجهٔ باقی‌مانده. هم‌روندی هر بالادست محدود شود؛ برای خواندن Idempotent از Hedged request با wait(FIRST_COMPLETED) استفاده کنید و با قطع Client کار پایین‌دست را لغو کنید. مثال: GET /orders/42/summary به TaskGroup با GET orders/42، GET payments?order=42 و GET shipping/42، هرکدام ۳۰۰ ms، درون asyncio.timeout(0.8) می‌رود؛ یک شکست ۲ کار دیگر را لغو می‌کند و 502/504 می‌دهد. چیزهایی که خودکار از شبکه عبور نمی‌کنند: مقدار ContextVar؛ شناسه را Header کنید، مانند OpenTelemetry. لغو؛ لغوشدن Client کار سرور را متوقف نمی‌کند مگر سرور قطع را تشخیص دهد. Back-pressure درون Process؛ برای بین سرویس‌ها Broker با سقف مصرف یا 429 با Retry-After لازم است. Retry و Idempotency در API Idempotency آمده‌اند.

دادهٔ توزیع‌شده (Distributed data): Replica، Cache، Shard و چند منطقه ​

asyncio ارتباط هم‌زمان با چند گرهٔ داده را ارزان می‌کند: Scatter-gather میان Shardها، جست‌وجوی Cache هم‌زمان یا خواندن نزدیک‌ترین نمونه (Replica). به همان اندازه اضافه‌باردادن هم ارزان می‌شود. سقف هم‌روندی از «هر Process» به «کل ناوگان» می‌رود؛ ۲۰ Worker با Semaphore(10) یعنی ۲۰۰ Query هم‌زمان به یک Shard. Lock و Semaphore این صفحه محلی‌اند؛ هماهنگی بین Processها به قفل ردیف یا Advisory lock پایگاه داده، Redis یا سرویس Lease نیاز دارد. هجوم Cache miss روی یک کلید، یا Cache stampede، داخل Process با asyncio.Lock برای هر کلید یا Future مشترک، یعنی Single flight، حل می‌شود؛ بین Processها به Redis lock یا ادغام درخواست در لایهٔ Cache نیاز است. تأخیر Replica و الگوهای Cache در Caching هستند.

مسیر افزایش مقیاس (Scaling path): ۱×، ۱۰×، ۱۰۰× ​

بارچه عوض می‌شودروش Async
1×؛ یک Processپیش‌فرض‌ها کافی به نظر می‌رسندبدون Blocking در async def؛ یک Client در هر Process؛ Timeout؛ Task قابل پیگیری؛ Debug mode در تست
10×؛ Worker حدود تعداد هسته و چند Replicaسقف‌های محلی ضرب می‌شوند؛ Deploy کار را از بین می‌برداندازهٔ Pool × Worker ≤ سقف سرور؛ تخلیه در خاموشی؛ شناسهٔ درخواست با ContextVar؛ Metric تأخیر حلقه؛ uvloop در Linux
100×؛ سرویس زیاد و Fan-out بالاتأخیر انتهایی، طوفان Retry، اتمام ظرفیت Thread poolDeadline propagation؛ سقف هر بالادست؛ ریزش بار (Load shedding) با --limit-concurrency و 503؛ انتقال CPU از لایهٔ وب به صف و Process pool؛ Load Shedding

آزمایشگاه (Lab) ​

همهٔ فرمان‌ها از docs/snippets/python/async-python-asyncio/ اجرا می‌شوند. خروجی «واقعی» با CPython 3.9.6 روی macOS با ۱۲ CPU و نسخه‌های ثابت تولید شده است. روی Python 3.12+ با انتشارهای جاری، خروجی‌ها جز شمارهٔ نسخه، ۲ تست ویژهٔ 3.11 که به‌جای Skipped شدن اجرا می‌شوند، و متن پیام‌های مشخص‌شده در صفحه، یکسان‌اند.

۱. نصب و اجرای تست‌ها؛ واقعی ​

python3 -m venv ~/venvs/apa                       # keep the venv outside the repo (.venv/ and *.egg-info are not git-ignored)
~/venvs/apa/bin/pip install '.[test]'             # or: pip install -r requirements.lock
export PYTHONDONTWRITEBYTECODE=1                  # pyproject sets -p no:cacheprovider
~/venvs/apa/bin/python -m pytest -s -rs
# BEFORE: /dashboard 0.574s, /health during it 0.554s
# AFTER: /dashboard 0.158s, /health during it 0.002s
# queue maxsize=5, 40 items, 4 consumers x 10 ms: {'processed': 40, 'max_qsize': 5, 'producer_wait_s': 0.088, 'elapsed_s': 0.11}
# 20 x 100 ms: sequential 2.072s | threads 0.133s | gather 0.136s | Semaphore(5) 0.439s | sync client in async def 2.068s
# worst heartbeat gap: time.sleep 0.211s, to_thread 0.011s, asyncio.sleep 0.013s
# os.cpu_count()=12 default executor max_workers=16
# 4 x cpu_burn(2000000): inline 0.42s, threads 0.37s, processes 0.18s
# SKIPPED [1] tests/test_cancellation.py:46: asyncio.TaskGroup / asyncio.timeout() are 3.11+
# SKIPPED [1] tests/test_tasks.py:68: asyncio.TaskGroup / asyncio.timeout() are 3.11+
# 43 passed, 2 skipped in 10.17s

رونوشت کامل شامل stderr حالت Debug در runs/pytest-fresh-install.txt است؛ همهٔ عددهای صفحه از آن‌اند. اجرای دوباره پس از بازترکردن ۲ Assert برای ماشین مشترک در runs/pytest-final-code.txt، خروجی 43 passed, 2 skipped in 9.32s داد؛ تصویر همان بود: ترتیبی ۲٫۰۵۳ ثانیه، gather برابر ۰٫۱۲۵ ثانیه، /health قبل ۰٫۵۶۹ ثانیه و بعد ۰٫۰۰۱ ثانیه. با uv روی Python 3.12+، فرمان uv run --extra test pytest -s مورد انتظار و اجرا نشده است چون uv روی ماشین ساخت نصب نیست؛ ۲ تست Skipped آنجا اجرا می‌شوند و انتظار موفقیت دارند.

20 GET requests x 100 ms upstream delay (real run, CPython 3.9.6, httpx 0.28.1)sync sequential (httpx.Client)2.07 ssync client inside async def2.07 sAsyncClient + Semaphore(5)0.44 s (4 waves of 5)AsyncClient + gather0.14 shttpx.Client + 20 threads0.13 s01 s2 sthreads match async for 20 calls; async wins on memory and at thousands of connections

۲. اندازه‌گیری مستقل Fan-out؛ واقعی ​

~/venvs/apa/bin/python -m app.fanout
# 20 GET requests, each answered after 100 ms by a local asyncio server
# sync sequential (httpx.Client)        2.082 s
# sync + ThreadPoolExecutor(20)         0.129 s
# async gather (httpx.AsyncClient)      0.142 s
# async gather + Semaphore(5)           0.439 s
# sync client inside async def          2.071 s

n و delay را در app/fanout.py تغییر دهید تا مقیاس را ببینید. اجرای ترتیبی با n × delay رشد می‌کند؛ gather نزدیک ۱ delay می‌ماند تا سقف اتصال، پیش‌فرض ۱۰۰ در httpx، یا Backlog سرور برسد. نسخهٔ Semaphore پله‌ای با ceil(n / limit) × delay رشد می‌کند.

۳. مسدودشدن حلقه را ببینید؛ واقعی ​

~/venvs/apa/bin/python -m pytest -s tests/test_offload.py -k heartbeat   # test_heartbeat_time_sleep_blocks_the_loop_to_thread_does_not
# worst heartbeat gap: time.sleep 0.211s, to_thread 0.011s, asyncio.sleep 0.013s
PYTHONASYNCIODEBUG=1 ~/venvs/apa/bin/python -m pytest -s tests/test_debug.py
# ... Executing <Task pending name='Task-1' coro=<main() running at <string>:13> ...> took 0.213 seconds

۴. Uvicorn کدام حلقه را اجرا می‌کند؟ واقعی ​

cd ../../../../pipeline/sources/async-python-asyncio/runs   # from the snippet dir: the probe ASGI app lives with the run logs
~/venvs/apa/bin/python probe_uvicorn_loops.py ~/venvs/apa/bin
# --loop auto: uvloop.Loop tokens=40
# --loop asyncio: asyncio.unix_events._UnixSelectorEventLoop tokens=40
# --loop uvloop: uvloop.Loop tokens=40

۵. TaskGroup و asyncio.timeout روی 3.11+؛ مورد انتظار، اجرا نشده ​

python3.12 -m venv ~/venvs/apa312 && ~/venvs/apa312/bin/pip install '.[test]'
~/venvs/apa312/bin/python -m pytest -q -k "taskgroup or timeout_block"
# expected: 2 passed  (taskgroup_fail_fast -> (["a failed"], ["b", "c"]); timeout_block -> "done" / "timed out")

با انتشارهای جاری روی 3.12+ می‌توان Pinها را به جدیدترین نسخه برد. JSON ذخیره‌شدهٔ PyPI در ۲۰۲۶-۱۱-۲۹: FastAPI 0.165.0 با requires_python >=3.11، بارگذاری ۲۰۲۶-۱۱-۱۸؛ httpx 0.29.0 با >=3.10، بارگذاری ۲۰۲۶-۱۱-۲۶؛ pytest-asyncio 1.5.0 و anyio 4.16.0. این مورد انتظار است و اجرا نشده.

برای توسعه‌دهندگان PHP/Laravel (For PHP/Laravel developers) ​

در PHP-FPM هر درخواست در Worker process مستقل و با وضعیت تازه اجرا می‌شود و هر فراخوانی همان Worker را مسدود می‌کند. حلقه‌ای برای مسدودکردن یا کاری برای لغو ندارید؛ هم‌روندی یعنی FPM Worker بیشتر. این همان ستون Thread برای هر درخواست در چرا وجود دارد است. دنیای PHP ۳ مدل Async مشابه Python را به‌شکل افزوده دارد. Fiberها (Fibers) از PHP 8.1 ابزار خود زبان‌اند: "Fibers represent full-stack, interruptible functions. Fibers may be suspended from anywhere in the call-stack". برخلاف Coroutine در Python به علامت‌گذاری async/await در زنجیرهٔ توابع نیاز ندارند: "the direct caller of the function does not need to change how it invokes the function"؛ اما برای کاربرد عملی کتابخانهٔ زمان‌بند می‌خواهند. ReactPHP همتای asyncio است: "ReactPHP is a low-level library for event-driven programming in PHP. At its core is an event loop" و Promise نقش Future را دارد. Swoole / Open Swoole افزونه‌ای با "an event loop, coroutine scheduler, servers, clients, and protocol implementations" است. Hookهای Runtime آن، توابع معمول I/O در PHP را از Coroutine آگاه می‌کنند؛ این به Go یا gevent نزدیک‌تر از asyncio است. Laravel Octane طبق مستندات "supercharges your application's performance by serving your application using high-powered application servers, including FrankenPHP, Open Swoole, Swoole, and RoadRunner. Octane boots your application once, keeps it in memory". بنابراین قواعد Process بلندعمر این صفحه را به Laravel می‌آورد: وضعیت درخواست در Singleton نماند و منبع ۱ بار باز شود. روی Swoole، Octane::concurrently اضافه می‌شود که Closureهایش "utilize Swoole's "task workers", and execute within an entirely different process than the incoming request"؛ یعنی Process pool، نه Coroutine روی ۱ حلقه. برای HTTP هم‌روند در یک درخواست، Http::pool در Laravel درخواست‌ها را "several requests … at the same time instead of issuing the requests sequentially" ارسال می‌کند.

php
<?php
// Laravel 13: the dashboard fan-out (compare app/after.py)
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
use Laravel\Octane\Facades\Octane;

// Concurrent HTTP from one request: the closest thing to AsyncClient + gather()
$responses = Http::pool(fn (Pool $pool) => [
    $pool->as('orders')->timeout(1)->get("$upstream/delay/100"),     // httpx.Timeout(1.0)
    $pool->as('invoices')->timeout(1)->get("$upstream/delay/100"),
    $pool->as('tickets')->timeout(1)->get("$upstream/delay/100"),
]);

// Octane on Swoole: closures run in Swoole task workers (another process),
// so this is closer to run_in_executor(process_pool, ...) than to gather()
[$users, $servers] = Octane::concurrently([
    fn () => User::all(),
    fn () => Server::all(),
]);

// Plain PHP 8.1 Fiber: the suspension primitive a scheduler builds on (no scheduler here)
$fiber = new Fiber(function (): string {
    $reply = Fiber::suspend('waiting for socket');   // like a coroutine yielding a Future
    return "got $reply";
});
$state = $fiber->start();                             // "waiting for socket"
$fiber->resume('data');                               // the "event loop" resumes it
echo $fiber->getReturn();                             // "got data"
PHP / LaravelPython asyncio
Worker در PHP-FPM برای هر درخواستRoute با def در Thread / Worker در WSGI
Fiber از 8.1Coroutine، اما بدون علامت‌گذاری async/await
Event loop و Promise در ReactPHPحلقهٔ asyncio و Future
Coroutine و Hook زمان اجرا در SwooleTask در asyncio؛ Python کتابخانهٔ Async می‌خواهد؛ Hookها شبیه gevent هستند
Swoole\Coroutine\Channelasyncio.Queue
Octane::concurrently([...])؛ Task worker در Process جدا در Swoolerun_in_executor(process_pool, ...) + gather
Worker بلندعمر OctaneWorker در Uvicorn با Lifespan
Http::timeout(1)httpx.Timeout(1.0)
کار صف‌شده با dispatch(new Job)صف کار Celery یا arq؛ نه create_task
sleep() در Coroutine Swoole با Hookawait asyncio.sleep()
Http::pool(fn (Pool $pool) => [...]) در LaravelAsyncClient + gather

نگاه Go (The Go angle) ​

انتخاب طراحی Go متفاوت است: در کد شما نه کلمهٔ async هست و نه Event loop. هر تابع می‌تواند Blocking باشد و Runtime، گوروتین‌ها (Goroutines) را میان Threadهای سیستم‌عامل و Network poller چندراهه می‌کند. تور Go: "A goroutine is a lightweight thread managed by the Go runtime." نتیجه‌ها روشن‌اند: فراخوانی Blocking فقط همان Goroutine را متوقف می‌کند و باگ «بستن حلقه» ندارید؛ کار CPU روی Threadهای GOMAXPROCS موازی است و GIL ندارد؛ مسئلهٔ رنگ‌آمیزی تابع (Function colouring)، یعنی «این تابع Async است پس فراخواننده هم باید باشد»، وجود ندارد. چیزی که Go با قرارداد اضافه می‌کند در asyncio درونی است: Cancellation با context.Context صریح منتقل می‌شود، طبق context، اما asyncio در await بعدی CancelledError تزریق می‌کند. Goroutine فراموش‌شده مثل Task رهاشده بی‌صدا نشت می‌کند. ابزار هم‌روندی ساخت‌یافته، errgroup.Group با WithContext، همتای TaskGroup است؛ Worker pool و Pipeline. کانال (Channel) نقش asyncio.Queue را دارد و قاعدهٔ Effective Go برای هر ۲ مناسب است: "Do not communicate by sharing memory; instead, share memory by communicating". مقالهٔ Pipeline آن را "a series of stages connected by channels" تعریف می‌کند. رقابت داده (Data race) که asyncio با ۱ Thread عمدتاً از آن دور می‌ماند، در Go مسئلهٔ جدی با Detector است؛ Race condition و Deadlock. مثال به‌روزرسانی گم‌شدهٔ بالا همتای Go با sync.Mutex دارد.

go
// Go: the bounded dashboard fan-out (compare app/after.py fetch_section + Semaphore)
func dashboard(ctx context.Context, client *http.Client, upstream string) (map[string]json.RawMessage, error) {
	ctx, cancel := context.WithTimeout(ctx, time.Second) // asyncio.timeout(1.0)
	defer cancel()
	g, ctx := errgroup.WithContext(ctx) // TaskGroup: first error cancels ctx for the rest
	g.SetLimit(10)                      // Semaphore(10)
	sections := []string{"orders", "invoices", "tickets", "shipments", "reviews"}
	results := make([]json.RawMessage, len(sections))
	for i := range sections {
		g.Go(func() error { // a goroutine, not a coroutine: may block freely
			req, _ := http.NewRequestWithContext(ctx, http.MethodGet, upstream+"/delay/100", nil)
			resp, err := client.Do(req) // blocking call: fine in Go
			if err != nil {
				return err // cancellation arrives as ctx.Err(), not as an exception
			}
			defer resp.Body.Close()
			results[i], err = io.ReadAll(resp.Body)
			return err
		})
	}
	if err := g.Wait(); err != nil { // like leaving `async with TaskGroup()`
		return nil, err
	}
	out := make(map[string]json.RawMessage, len(sections))
	for i, s := range sections {
		out[s] = results[i]
	}
	return out, nil
}
موضوعPython asyncioGo
واحد هم‌روندیTask؛ Coroutine روی یک حلقهGoroutine؛ زمان‌بندی Runtime روی چند Thread
فراخوانی Blocking در Goroutine و Taskهمهٔ Taskهای حلقه را متوقف می‌کندفقط همان Goroutine را
CPU موازیروی حلقه ندارد؛ Process لازم استبله؛ GOMAXPROCS
Function colouringasync def باید await شودندارد
Channel در برابر Queueasyncio.Queue(maxsize)make(chan T, n)
Fan-out محدودSemaphore + gather / TaskGrouperrgroup + SetLimit
لغوtask.cancel() → CancelledError در await بعدیلغو context → بررسی ctx.Done() / ctx.Err()
مهلتasyncio.timeout، wait_forcontext.WithTimeout
کار نشت‌کردهTask بدون ارجاعGoroutine leak
مقدار هر درخواستContextVarcontext.WithValue با احتیاط
انتخاب میان چند انتظارwait(FIRST_COMPLETED)دستور select
کشف Raceکم به‌دلیل یک Thread؛ ابزار داخلی نداردgo test -race

بدفهمی‌های رایج (Common misconceptions) ​

باورواقعیت
async def کد را سریع می‌کندانتظارها را هم‌پوشان می‌کند؛ Blocking و CPU همان‌قدر کندند و بقیهٔ Taskها را هم متوقف می‌کنند
asyncio، Coroutineها را موازی اجرا می‌کندیک حلقه یک Thread دارد؛ در هر لحظه یک Coroutine اجرا می‌شود
فراخوانی تابع async def آن را اجرا می‌کندفقط شیء Coroutine می‌دهد؛ تا await یا Task نشود اجرا نمی‌شود
await x()، تابع x را در پس‌زمینه اجرا می‌کندهمین حالا x را اجرا می‌کند و منتظرش می‌ماند؛ هم‌روندی Task می‌خواهد
یک Thread یعنی نبود Race conditionTaskها در await تعلیق‌کننده جابه‌جا می‌شوند؛ خواندن-await-نوشتن در قطعه‌کد 49 از 50 تغییر را گم کرد
هر await فرصت اجرا به بقیه می‌دهدفقط await تعلیق‌کننده؛ Future تمام‌شده یا Coroutine بدون مکث جابه‌جا نمی‌کند؛ await asyncio.sleep(0) می‌کند
gather با اولین خطا بقیه را لغو می‌کندنمی‌کند؛ TaskGroup از 3.11+ و گروه AnyIO می‌کنند
create_task و فراموش‌کردن درست استحلقه فقط Weak reference دارد؛ خطا گم می‌شود و خاموشی آن را لغو نمی‌کند
task.cancel() فوری متوقف می‌کنددرخواست CancelledError در await بعدی است؛ حلقهٔ CPU بدون await قابل لغو نیست
گرفتن CancelledError و ادامه‌دادن مقاوم استTaskGroup، timeout() و خاموشی را خراب می‌کند؛ پس از پاک‌سازی دوباره پرتاب کنید
except TimeoutError همه‌جا مهلت wait_for را می‌گیرددر 3.9/3.10 کلاس متفاوت asyncio.TimeoutError پرتاب می‌شود
wait(timeout=...) ناتمام‌ها را لغو می‌کنددر pending برمی‌گرداند؛ شما لغو می‌کنید
to_thread، CPU را موازی می‌کندGIL، Bytecode خالص را ترتیبی می‌کند؛ 0.37 s در برابر 0.42 s واقعی؛ Processها 0.18 s شدند
Thread pool پیش‌فرض نامحدود استmin(32, cpu_count + 4)؛ اینجا 16؛ Route با def در FastAPI از 40 توکن AnyIO استفاده می‌کند
Client همگام در async def اگر سریع باشد اشکالی نداردهر فراخوانی حلقه را نگه می‌دارد؛ 20 فراخوانی زیر gather، 2.07 s شدند
asyncio.Lock دادهٔ مشترک با Thread را محافظت می‌کندابزارهای asyncio، Thread-safe نیستند؛ threading.Lock یا call_soon_threadsafe لازم است
threading.local درخواست‌ها را جدا می‌کندهمهٔ Taskها Thread حلقه را شریک‌اند؛ ContextVar لازم است
صف نامحدود امن‌تر استمصرف‌کنندهٔ کند را به حافظه و تأخیر نامحدود تبدیل می‌کند؛ سقف و سیاست بگذارید
nest_asyncio راه‌حل استراه موقت Notebook است؛ درون asyncio را Patch می‌کند و uvloop را پشتیبانی نمی‌کند
GIL از Python 3.13 حذف شدهفقط در ساخت جداگانهٔ Free-threaded؛ 3.13t آزمایشی و 3.14t پشتیبانی‌شده؛ پیش‌فرض GIL دارد
uvloop شیوهٔ کدنویسی را عوض می‌کندAPI همان asyncio است؛ فقط پیاده‌سازی حلقه عوض می‌شود

برگهٔ تقلب (Cheat sheet) ​

موضوعبه خاطر بسپارید
اجراasyncio.run(main())؛ داخل Coroutine فقط await
هم‌روندیcreate_task، gather، TaskGroup از 3.11+، گروه AnyIO
نگهداری Taskهر Task را در Set و Callback پایان یا TaskGroup ذخیره کنید؛ در خاموشی تخلیه کنید
gatherترتیب ورودی؛ اولین خطا منتقل می‌شود و بقیه ادامه می‌دهند؛ return_exceptions=True جمع می‌کند
مسابقه / جریانwait(FIRST_COMPLETED) و لغو pending؛ as_completed
لغوtask.cancel() → CancelledError در await بعدی؛ پاک‌سازی در finally و پرتاب دوباره
Shieldawait shield(task) و نگهداری ارجاع task
مهلتwait_for(aw, t)؛ async with asyncio.timeout(t) در 3.11+؛ fail_after/move_on_after در AnyIO؛ گرفتن asyncio.TimeoutError روی ≤ 3.10
سقفSemaphore(n) دور هر فراخوانی؛ Queue(maxsize) محدود برای Pipeline
I/O مسدودکنندهawait asyncio.to_thread(f, ...)؛ در FastAPI، Route با def یا run_in_threadpool
اندازهٔ PoolExecutor پیش‌فرض min(32, cpu + 4)؛ AnyIO: 40 توکن؛ httpx: 100 اتصال و 20 Keep-alive
CPUProcessPoolExecutor با run_in_executor؛ ساخت یک‌باره
وضعیت درخواستContextVar؛ set → Token → reset در finally
DebugPYTHONASYNCIODEBUG=1 یا asyncio.run(main(), debug=True)؛ ثبت Callback کند ≥ 100 ms
HTTPیک httpx.AsyncClient در هر Process با Limits و Timeout صریح
حلقهUvicorn --loop auto یعنی uvloop اگر نصب باشد؛ Windows: Proactor
تست@pytest.mark.asyncio در Strict یا @pytest.mark.anyio؛ هر دو در Auto نباشند
GILThread برای I/O، Process برای CPU؛ Free-threaded انتخابی است

خودآزمایی: پرسش و پاسخ (Self-check: questions & answers) ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — تفاوت هم‌روندی و اجرای موازی چیست و asyncio کدام را می‌دهد؟ حیاتی ​

پاسخ

پاسخ: هم‌روندی (Concurrency) یعنی چند Task در جریان‌اند و قدم‌هایشان در هم می‌رود؛ اجرای موازی (Parallelism) یعنی چند کار در یک لحظه روی هسته‌های مختلف اجرا می‌شوند. asyncio هم‌روندی روی ۱ Thread می‌دهد: وقتی Coroutine منتظر I/O است دیگری اجرا می‌شود. CPU موازی در CPython پیش‌فرض به Process، کد C آزادکنندهٔ GIL یا ساخت Free-threaded نیاز دارد. هم‌روندی و اجرای موازی را ببینید.

۲ — Route با async def، تابع requests.get یا httpx.Client.get را صدا می‌زند؛ بقیهٔ درخواست‌ها چه می‌شوند و راه اصلاح چیست؟ حیاتی ​

پاسخ

پاسخ: فراخوانی در تمام مدت Thread حلقه را می‌بندد؛ پس همهٔ درخواست‌های آن Worker، حتی /health ساده، منتظر می‌مانند. اندازه‌گیری: ۰٫۵۵۴ ثانیه انتظار هنگام داشبورد ۰٫۵۷۴ ثانیه‌ای. از httpx.AsyncClient یک‌بار بازشده در Lifespan استفاده کنید، یا Route را def کنید تا FastAPI در Thread pool مربوط به AnyIO اجرا کند، یا فراخوانی را در asyncio.to_thread بگذارید. قبل و بعد را ببینید.

۳ — asyncio.create_task() چه می‌کند و چرا باید مقدار بازگشتی را نگه دارید؟ حیاتی ​

پاسخ

پاسخ: Coroutine را در Task می‌گذارد و زمان‌بندی می‌کند؛ Task در await بعدی سازنده آغاز می‌شود. حلقه فقط Weak reference دارد، پس Task بدون ارجاع می‌تواند پیش از پایان جمع‌آوری شود، استثنایش دیده نشود و "Task exception was never retrieved" بدهد؛ هنگام خاموشی هم کسی لغوش نمی‌کند. Task را در Set همراه Callback پایان نگه دارید یا TaskGroup استفاده کنید. Taskها را ببینید.

۴ — در gather(a(), b())، کار a پس از ۱۰ ms خطا می‌دهد؛ b چه می‌شود و return_exceptions=True و TaskGroup چه فرقی دارند؟ حیاتی ​

پاسخ

پاسخ: استثنای a فوری به Task منتظر منتقل می‌شود و b ادامه می‌دهد؛ gather آن را لغو نمی‌کند. با return_exceptions=True استثنا پرتاب نمی‌شود و شیء خطا در جای a در فهرست می‌آید. TaskGroup از 3.11+، کار b را لغو می‌کند، منتظر پایان لغو می‌ماند و ExceptionGroup می‌دهد. gather و TaskGroup را ببینید.

۵ — لغو در asyncio چگونه کار می‌کند و مشکل except asyncio.CancelledError: pass چیست؟ حیاتی ​

پاسخ

پاسخ: task.cancel() فقط درخواست می‌دهد؛ در await بعدی داخل Task، CancelledError پرتاب می‌شود و پشته از finally و async with عبور می‌کند. اگر خطا بیرون برود Task لغوشده می‌شود. بلعیدن خطا Task را «موفق» تمام می‌کند و TaskGroup، asyncio.timeout() و خاموشی آرام را که به لغو متکی‌اند خراب می‌کند. پاک‌سازی کنید و دوباره پرتاب کنید؛ لغو.

۶ — در Python 3.9 و 3.12 چگونه برای یک فراخوانی و برای کل بلوک Timeout می‌گذارید؟ مهم ​

پاسخ

پاسخ: یک فراخوانی در همهٔ نسخه‌ها با await asyncio.wait_for(aw, timeout) محدود و در سررسید لغو می‌شود. برای بلوک در 3.11+ از async with asyncio.timeout(t) و در قدیمی‌ترها از fail_after یا move_on_after در AnyIO استفاده کنید. در 3.9/3.10 باید asyncio.TimeoutError را بگیرید که با TimeoutError داخلی متفاوت است؛ از 3.11 یک کلاس‌اند. مهلت Client با httpx.Timeout را هم اضافه کنید؛ مهلت.

۷ — چرا برنامهٔ فقط Coroutine هم Race condition دارد و چطور اصلاح می‌شود؟ مهم ​

پاسخ

پاسخ: Taskها هر جا await واقعاً معلق شود جابه‌جا می‌شوند؛ await نتیجهٔ آماده چنین نمی‌کند. اگر Task وضعیت مشترک را بخواند، روی فراخوانی DB یا حتی sleep(0) معلق شود و بعد بنویسد، دیگران در این فاصله همان مقدار قدیمی را می‌خوانند؛ قطعه‌کد ۴۹ مورد از ۵۰ افزایش را گم کرد. دور خواندن-await-نوشتن asyncio.Lock بگیرید، await میانی را حذف کنید یا به‌روزرسانی را در پایگاه داده اتمی انجام دهید. ابزارهای هماهنگی را ببینید.

۸ — Back-pressure چیست و asyncio.Queue(maxsize=...) چگونه آن را ایجاد می‌کند؟ مهم ​

پاسخ

پاسخ: پس‌فشار (Back-pressure) یعنی مصرف‌کنندهٔ کند تولیدکننده را کند کند تا کار انباشته نشود. در صف محدود await queue.put() هنگام پرشدن منتظر می‌ماند و سرعت تولید به مصرف محدود می‌شود؛ در اندازه‌گیری صف از ۵ بیشتر نشد و تولیدکننده ۰٫۰۸۸ ثانیه منتظر ماند. اگر تولیدکننده نمی‌تواند صبر کند، put_nowait و رد درخواست با QueueFull و 429/503 یا حذف کار را انتخاب کنید. صف‌ها را ببینید.

۹ — چه وقت asyncio.to_thread و چه وقت ProcessPoolExecutor لازم است و اندازهٔ Thread pool پیش‌فرض چقدر است؟ مهم ​

پاسخ

پاسخ: to_thread برای I/O مسدودکنندهٔ بدون همتای Async، مانند SDK همگام، sqlite3 و فایل‌خوانی است؛ Worker منتظر می‌ماند و حلقه آزاد است. CPU خالص به Process pool می‌رود چون Threadها GIL مشترک دارند؛ زمان واقعی Thread برابر ۰٫۳۷، مستقیم ۰٫۴۲ و Process برابر ۰٫۱۸ ثانیه بود. Executor پیش‌فرض min(32, os.cpu_count() + 4) Worker دارد؛ روی ۱۲ CPU ۱۶ است و از 3.13 از process_cpu_count استفاده می‌کند. Routeهای def در FastAPI محدودکنندهٔ جداگانهٔ ۴۰ توکنی AnyIO دارند؛ اجرای کد Blocking.

۱۰ — کد Async را با pytest چگونه تست می‌کنید و چرا پروژه Strict mode دارد؟ مهم ​

پاسخ

پاسخ: افزونه لازم است: pytest-asyncio با @pytest.mark.asyncio یا افزونهٔ داخلی AnyIO با @pytest.mark.anyio و Fixture به‌نام anyio_backend. pytest تنها تست Async را با "async def functions are not natively supported" ناموفق می‌کند. Auto mode ۲ افزونه با هم تداخل دارد، پس Strict mode و Marker صریح اجازه می‌دهد هر ۲ در یک مجموعه کار کنند. برنامهٔ FastAPI با httpx.ASGITransport روی حلقهٔ تست اجرا می‌شود؛ Lifespan را خودتان وارد شوید. تست Async را ببینید.

۱۱ — contextvars چه مسئله‌ای را حل می‌کند که threading.local نمی‌تواند؟ تکمیلی ​

پاسخ

پاسخ: همهٔ Taskهای حلقه ۱ Thread دارند، پس مقدار Thread-local یک درخواست برای درخواست دیگر همان Worker هم دیده می‌شود. ContextVar برای هر Task است؛ Task در کپی Context سازنده اجرا می‌شود، مقدار از awaitها عبور می‌کند، to_thread آن را به Worker کپی می‌کند و تغییر فرزند به والد نشت نمی‌کند. برای شناسهٔ درخواست، Tenant و Span ردیابی مناسب است؛ contextvars.

۱۲ — GIL و ساخت Free-threaded برای کد asyncio چه چیزی را عوض می‌کنند؟ تکمیلی ​

پاسخ

پاسخ: برای کد روی Event loop چیزی عوض نمی‌شود؛ در هر ۲ مورد ۱ Thread است و GIL هنگام I/O آزاد می‌شود. GIL برای Thread pool مهم است: در ساخت پیش‌فرض CPU-bound در Threadها موازی اجرا نمی‌شود. ساخت Free-threaded در 3.13 آزمایشی و از 3.14 رسماً پشتیبانی‌شده اما اختیاری است؛ با حذف GIL چند هسته را در اختیار Threadها می‌گذارد. طبق HOWTO، هزینهٔ تک‌ریسمانی حدود ۱ تا ۸ درصد است و بعضی افزونه‌های C دوباره GIL را فعال می‌کنند؛ GIL.

واژه‌نامه (Glossary) ​

اصطلاحمعنا
هم‌روندی و اجرای موازی (Concurrency vs parallelism)پیش‌رفت درهم‌تنیدهٔ چند Task در برابر اجرای هم‌زمان روی چند هسته
قفل سراسری مفسر (GIL)در CPython پیش‌فرض فقط یک Thread در هر لحظه Bytecode اجرا می‌کند
Python بدون GIL (Free-threaded Python)ساخت CPython بدون GIL؛ --disable-gil، python3.13t/3.14t؛ PEP 703 و PEP 779
PYTHON_GILمتغیر محیطی فعال‌کردن دوبارهٔ GIL در ساخت Free-threaded
وابسته به انتظار (I/O-bound)بیشتر زمان منتظر شبکه، دیسک یا پایگاه داده است
وابسته به پردازش (CPU-bound)بیشتر زمان صرف محاسبه می‌شود
فراخوانی مسدودکننده (Blocking call)Thread را تا پایان نگه می‌دارد؛ time.sleep، requests و Driver همگام
I/O غیرمسدودکننده (Non-blocking I/O)سوکت غیرمسدودکننده همراه اعلان آمادگی Selector
حلقهٔ رویداد (Event loop)زمان‌بند asyncio با Timer، Callback آماده و Selector؛ همهٔ Taskها روی یک Thread
انتخاب‌گر آمادگی (Selector)پوشش API آمادگی سیستم‌عامل؛ selectors با epoll، kqueue، poll و select
حلقهٔ مبتنی بر تکمیل (Proactor)حلقهٔ Windows با IOCP؛ از 3.8 پیش‌فرض آنجاست
uvloopجایگزین سازگار حلقهٔ asyncio روی libuv، نوشته‌شده با Cython؛ پیش‌فرض Uvicorn اگر نصب باشد
تابع بازخوان / دستگیره (Callback / handle)تابع زمان‌بندی‌شده با call_soon / call_later؛ چیزی که حلقه واقعاً اجرا می‌کند
تابع کوروتین (Coroutine function)تابع تعریف‌شده با async def
کوروتین (Coroutine)شیء خروجی تابع Coroutine؛ با await یا Task اجرا می‌شود
async defتعریف تابع Coroutine؛ PEP 492، Python 3.5
awaitCoroutine جاری را تا پایان Awaitable معلق می‌کند
قابل انتظار (Awaitable)Coroutine، Task، Future یا هر شیء دارای __await__
نتیجهٔ آینده (Future)جای خالی نتیجه در سطح پایین همراه Callback؛ asyncio.Future
وظیفه (Task)Futureای که Coroutine را روی حلقه پیش می‌برد؛ asyncio.Task
create_taskزمان‌بندی Coroutine در Task و برگرداندن Task
اجرا و رهاکردن (Fire and forget)شروع Task بدون await؛ فقط با ارجاع نگه‌داشته‌شده و رسیدگی به خطا امن است
ارجاع Task (Task reference)ارجاع قوی که نگه می‌دارید؛ حلقه فقط ارجاع ضعیف دارد
کارخانهٔ Task مشتاق (Eager task factory)گزینهٔ 3.12+ برای اجرای همگام Task تازه تا نخستین تعلیق
gatherاجرای هم‌روند Awaitableها با نتیجه به ترتیب ورودی
return_exceptionsپرچم gather برای بازگرداندن استثنا به‌عنوان مقدار به‌جای پرتاب اولین خطا
TaskGroupContext manager ناهمگام 3.11+، مالک Taskها؛ لغو هم‌گروهی در شکست و پرتاب ExceptionGroup
ExceptionGroup / except*پرتاب چند استثنا با هم و رسیدگی بر اساس نوع؛ PEP 654، 3.11
as_completedپیمایش Awaitableها به ترتیب تکمیل
waitانتظار Set تا FIRST_COMPLETED، FIRST_EXCEPTION یا ALL_COMPLETED؛ خروجی (done, pending)
FIRST_COMPLETEDبازگشت wait به‌محض پایان یا لغو هر Future
لغو (Cancellation)درخواست توقف Task؛ تحویل CancelledError در await بعدی
CancelledErrorاستثنای لغو؛ از 3.8 زیر BaseException
shieldمحافظت Awaitable داخلی در برابر لغو Task بیرونی
مهلت (Timeout)سررسیدی که پس از آن کار لغو و TimeoutError پرتاب می‌شود
wait_forمهلت یک Awaitable؛ در انقضا لغوش می‌کند
asyncio.timeoutContext manager ناهمگام 3.11+ برای سررسید یک بلوک
هم‌روندی ساخت‌یافته (Structured concurrency)هر Task حوزهٔ والد دارد که منتظرش می‌ماند و در شکست لغوش می‌کند
AnyIOکتابخانهٔ Structured concurrency روی asyncio و Trio؛ پایهٔ Starlette و FastAPI
حوزهٔ لغو (Cancel scope)Context manager در AnyIO/Trio با لغو، تودرتویی، Shield و سررسید
لغو سطحی و لبه‌ای (Level vs edge cancellation)AnyIO در Scope لغوشده در هر yield دوباره لغو می‌کند؛ asyncio یک بار تحویل می‌دهد
قفل (Lock)Mutex در asyncio برای Task، نه Thread
شمارندهٔ مجوز (Semaphore)ورود حداکثر n Task به بلوک؛ سقف معمول Concurrency
رویداد (Event)پرچمی که با set همهٔ منتظرها را آزاد می‌کند
شرط (Condition)Lock و صف انتظار برای گزاره‌های روی وضعیت مشترک
صف (Queue)FIFO در asyncio با maxsize اختیاری؛ put/get/task_done/join
تولیدکننده/مصرف‌کننده (Producer consumer)Task تولیدکننده صف را پر و Task مصرف‌کننده آن را خالی می‌کند
پس‌فشار (Back-pressure)کندکردن تولیدکننده توسط مصرف‌کنندهٔ کند؛ صف محدود یا رد درخواست
to_threadابزار 3.9+ برای اجرای تابع در Executor پیش‌فرض با Context جاری
run_in_executorاجرای تابع در Executor معین یا پیش‌فرض و await کردن Future آن
ThreadPoolExecutorThread pool در concurrent.futures؛ Executor پیش‌فرض حلقه
ProcessPoolExecutorProcess pool در concurrent.futures برای CPU-bound
اندازهٔ Executor پیش‌فرض (Default executor size)min(32, os.cpu_count() + 4) در 3.8–3.12؛ process_cpu_count از 3.13
multiprocessingماژول استاندارد Process، Pool، Queue و حافظهٔ مشترک
مولد ناهمگام (Async generator)async def دارای yield، مصرف با async for؛ PEP 525
async forحلقه با قدم دریافت بعدی قابل await؛ __aiter__/__anext__
async withContext manager با ورود/خروج قابل await؛ __aenter__/__aexit__
مدیر زمینهٔ ناهمگام (Async context manager)شیء دارای __aenter__/__aexit__ یا ساخته‌شده با @asynccontextmanager
contextvars / ContextVarمتغیر Context برای هر Task؛ PEP 567، 3.7
asyncio.runساخت حلقه، اجرای Coroutine و پاک‌سازی Task، Generator و Executor پیش‌فرض
loop.run_until_completeسطح پایین: اجرای حلقه تا پایان یک Future
nest_asyncioPatch ثالث برای asyncio.run تودرتو؛ راه موقت Notebook
PYTHONASYNCIODEBUGمتغیر محیطی فعال‌کردن Debug mode در asyncio
حالت اشکال‌زدایی (Debug mode)ثبت Callback کند، محل ساخت Coroutine بی‌await و فراخوانی از Thread اشتباه
آستانهٔ Callback کند (Slow callback duration)loop.slow_callback_duration؛ پیش‌فرض 0.1 s برای هشدار Debug
"coroutine was never awaited"RuntimeWarning هنگام جمع‌آوری Coroutine اجرا‌نشده
Client ناهمگام httpx (httpx AsyncClient)HTTP Client با Connection pool؛ یکی برای هر Process
محدودیت اتصال (Connection limits)httpx.Limits؛ پیش‌فرض max_connections برابر 100، max_keepalive_connections برابر 20 و keepalive_expiry برابر 5 s
حلقهٔ Uvicorn (Uvicorn loop)گزینهٔ --loop با auto، asyncio یا uvloop؛ یک حلقه در هر Worker
Thread pool در FastAPI برای Route با defعملیات def با anyio.to_thread.run_sync و 40 توکن اجرا می‌شود
run_in_threadpool در Starletteawait anyio.to_thread.run_sync(func)؛ Offload یک فراخوانی از async def
pytest-asyncioافزونهٔ pytest برای @pytest.mark.asyncio؛ حالت Strict و Auto
افزونهٔ pytest در AnyIO (AnyIO pytest plugin)همراه AnyIO؛ @pytest.mark.anyio و Fixture به‌نام anyio_backend
خاموشی آرام (Graceful shutdown)توقف کار تازه، تخلیه، لغو و await کار باقی‌مانده و بستن Client
گوروتین (Goroutine)Thread سبک زمان‌بندی‌شده با Runtime Go؛ می‌تواند آزادانه Blocking باشد
کانال (Channel)مجرای نوع‌دار میان Goroutineها در Go؛ همتای asyncio.Queue
Fiber در PHP (PHP Fibers)تابع تمام‌پشتهٔ قابل تعلیق از PHP 8.1
PHP Swoole / Open Swooleافزونه‌های PHP با Event loop، Coroutine، Server و Client
Laravel Octaneبستهٔ سرو برنامه با Worker بلندعمر؛ FrankenPHP، Swoole، Open Swoole و RoadRunner
ReactPHPکتابخانهٔ Event loop برای PHP
SQLAlchemy / SQLModel / AlembicORM با افزونهٔ asyncio، لایهٔ ORM با Pydantic و ابزار Migration
Uvicorn / Starlette / FastAPIسرور ASGI، ابزار ASGI مبتنی بر AnyIO و Framework ساخت API

منابع (References) ​

ساخته‌شده توسط Morteza Negahi