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_GIL | GIL و Python بدون GIL |
| کدام فراخوانی Blocking است | I/O-bound و CPU-bound |
selectors، epoll، kqueue و uvloop | Event loop |
async def، await، Coroutine، Awaitable و Future | Coroutine و 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 scope | AnyIO و همروندی ساختیافته |
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 و @asynccontextmanager | Generator و Context manager ناهمگام |
| شناسهٔ درخواست در هر خط Log | contextvars |
asyncio.run، run_until_complete و nest_asyncio | نقطهٔ ورود و حلقهٔ تودرتو |
PYTHONASYNCIODEBUG، Callback کند و "never awaited" | اشکالزدایی |
httpx.AsyncClient، Limits و Timeout | Client ناهمگام 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 شبکه با کتابخانهٔ Async | httpx.AsyncClient، asyncpg، redis.asyncio | await + gather/TaskGroup | مشکلی ندارد؛ کاربرد اصلی همین است | 20 × 100 ms در 0.14 s |
| I/O شبکه با کتابخانهٔ Sync | requests، httpx.Client، boto3، راهانداز Sync پایگاه داده | asyncio.to_thread یا Route با def | در async def ترتیبی میشود و حلقه را میبندد | 2.07 s؛ انتظار /health برابر 0.55 s |
| خواب یا عقبنشینی (Backoff) | تأخیر تلاش مجدد | await asyncio.sleep | time.sleep همهٔ Taskها را متوقف میکند | فاصلهٔ Heartbeat: 0.211 s در برابر 0.013 s |
I/O فایل و sqlite3 | خواندن گزارش، پایگاه دادهٔ محلی | to_thread | حلقه را میبندد | اجرای کد Blocking |
| CPU در Python خالص | تجزیه، قیمتگذاری، پردازش تصویر در Python | ProcessPoolExecutor | Thread بهخاطر GIL سریعتر نمیشود | 4 کار: مستقیم 0.42 s، Threadها 0.37 s، Processها 0.18 s |
| افزونهٔ C که GIL را آزاد میکند | hashlib، zlib، NumPy | Thread pool | مشکلی ندارد؛ Threadها موازی اجرا میشوند | اندازهگیری نشده |
| فراخوانی همزمان بیشازحد | 10,000 URL | Semaphore یا 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 بدون await | RuntimeWarning: coroutine 'forgotten' was never awaited | همیشه در stderr |
| شکست Task بدون خواندن نتیجه | Task exception was never retrieved | Logger با نام asyncio، هنگام جمعآوری حافظه |
| بستن حلقه با Task معلق | Task was destroyed but it is pending! | Logger با نام asyncio |
| نگهداشتن حلقه بیش از 100 ms در Callback | Executing <Task pending name='Task-1' ...> took 0.213 seconds | Logger با نام asyncio، فقط Debug mode |
asyncio.run() داخل حلقهٔ در حال اجرا | RuntimeError: asyncio.run() cannot be called from a running event loop | استثنا |
asyncio.TaskGroup روی 3.9/3.10 | AttributeError: 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 با def | Event 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 exitPython
قبل (Before)
یک نقطهٔ پایانی (Endpoint) داشبورد ۵ بخش سفارش، صورتحساب، تیکت، محموله و نظر را از سرویس داخلی میگیرد؛ هر پاسخ ۱۰۰ ms زمان میبرد. تابع async def است و غیرمسدودکننده به نظر میرسد، اما داخلش httpx.Client همگام درخواستها را یکییکی میفرستد، با time.sleep «رندر» میکند، با asyncio.create_task() ۱ Task ثبت ممیزی میسازد و ارجاعش را دور میاندازد؛ آن Task هم CancelledError را میبلعد.
"""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 را کجا اجرا میکنند.
"""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.
"""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 داشبورد گیر کرده بود.
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 را دارد:
"""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")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 مجموعهٔ تست مشترک داشته باشند:
[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"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)
همروندی و اجرای موازی (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 | زمانبند سیستمعامل | بله | پشتهٔ Thread | CPU در 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، مرحلهٔ دوم |
| PyPy | GIL دارد | ندارد | پیادهسازی جایگزین |
اصلاح / روش استفاده: در ساخت پیشفرض برای 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 / aiohttp | to_thread |
psycopg2، pymysql، sqlite3 | بله | asyncpg، psycopg 3 async، aiomysql، aiosqlite، AsyncSession در SQLAlchemy | to_thread / Route با def |
redis.Redis | بله | redis.asyncio.Redis | to_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_exec | to_thread |
| boto3 | بله | aiobotocore؛ طبق README، Client ناهمگام AWS بر پایهٔ botocore و aiohttp/asyncio؛ یا aioboto3 | to_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؛ اختیاری Windows | selectors.DefaultSelector؛ epoll / kqueue / poll / select | asyncio.run | واقعی در macOS: _UnixSelectorEventLoop |
ProactorEventLoop | پیشفرض Windows از 3.8 | IOCP | asyncio.run در Windows | پشتیبانی زیرپردازه و Pipe |
uvloop Loop | Linux و macOS؛ بدون Windows | libuv، Cython | uvloop.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 شود، وگرنه asyncio | uvicorn[standard]، uvloop را نصب میکند | مستندات Uvicorn: "not compatible with Windows or PyPy" |
| Trio / Backend trio در AnyIO | همه | حلقهٔ خود Trio | anyio.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 را نشان میدهد.
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 coroutine | close() |
| Task | create_task، ensure_future، gather، TaskGroup.create_task | فوری زمانبندی؛ شروع در await بعدی سازنده | بله؛ همان نتیجه | task.cancel() |
| Future | loop.create_future()، run_in_executor | وقتی کسی نتیجه را تعیین کند | بله | fut.cancel() |
concurrent.futures.Future | Poolهای Thread/Process | داخل Worker | نه؛ تبدیل با asyncio.wrap_future | cancel() پیش از شروع |
| مولد ناهمگام (Async generator) | async def با yield | هر قدم async for | کاربرد ندارد | aclose() |
اصلاح / روش استفاده:
"""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())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 در اندازهگیری است.
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 |
|---|---|---|---|---|
| همگروهیها در اولین خطا | ادامه میدهند | ادامه میدهند | لغو میشوند | لغو میشوند |
| خروجی | اولین استثنا | فهرست دارای استثنا | ExceptionGroup | ExceptionGroup؛ 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 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 همیشه لغو صریح کاری را بگذارید که دیگر لازم نیست.
لغو (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: دور await | CancelledError را در 3.8+ نمیگیرد | همین درست است |
except BaseException: یا except: خالی | آن را میگیرد | دوباره پرتاب کنید |
اصلاح / روش استفاده:
"""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)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) | بلوک | لغو بلوک و TimeoutError | 3.11+ | reschedule()، timeout_at() |
asyncio.wait(aws, timeout=t) | Set | (done, pending)؛ بدون لغو | همه | بدون استثنا |
anyio.fail_after(t) | بلوک یا Cancel scope | TimeoutError | AnyIO 3+ | روی 3.9 کار میکند |
anyio.move_on_after(t) | بلوک | خروج بیصدا و scope.cancelled_caught | AnyIO 3+ | جایگزینهای Best effort |
httpx.Timeout(t, connect=...) | یک مرحلهٔ درخواست HTTP | زیرکلاسهای httpx.TimeoutException | httpx | پیشفرض "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 group | asyncio.TaskGroup، tg.create_task(coro) | anyio.create_task_group()، tg.start_soon(fn, *args) |
| انتظار آمادگی فرزند | Event دستی | await tg.start(fn) و task_status.started() |
| بلوک Timeout | asyncio.timeout(t) | fail_after(t) / move_on_after(t) |
| محافظت (Shield) | asyncio.shield(aw) برای یک Awaitable | CancelScope(shield=True) برای بلوک |
| معنای لغو | Edge | Level در Scope |
| استثنای لغو | asyncio.CancelledError | anyio.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.Lock | 1 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.Lock | 1 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-pressure | await q.put(x) | تولیدکنندهٔ قابل کندشدن، مثل Pipeline داخلی |
| رد درخواست | q.put_nowait(x) → QueueFull → 503 / 429 | Client دارای امکان Retry |
| حذف جدیدترین / قدیمیترین | put_nowait در try یا get_nowait() سپس put | سنجه، Telemetry، قیمت زنده |
| قطع مصرفکنندهٔ کند | پرشدن صف Client → بستن | WebSocket و Fan-out در SSE |
| ذخیرهٔ پایدار | Redis Streams، RabbitMQ، Kafka، SQS | نیاز به بقا پس از Restart؛ پیامرسانی |
اصلاح / روش استفاده:
"""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),
}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اجرای کد 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 در AnyIO | 40 توکن؛ CapacityLimiter | بله | کد AnyIO / Starlette |
await starlette.concurrency.run_in_threadpool(f, *a) | Threadهای Worker در AnyIO | 40 توکن | بله | داخل Route با async def؛ نام واقعی Thread: AnyIO worker thread |
Route با def یا Dependency همگام FastAPI | Threadهای Worker در AnyIO | 40 توکن | بله | تمام Route همگام است |
loop.run_in_executor(ProcessPoolExecutor(), f) | Processها | os.process_cpu_count() از 3.13+ | نه؛ Pickle میشود | کار CPU-bound |
اصلاح / روش استفاده:
"""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() - startfrom __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 لازم نیست:
-- 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 | بله | زیاد؛ یک بار برای هر Worker | Pickle | CPU از 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__؛ پرتاب StopAsyncIteration | Cursor، مصرفکنندهٔ پیام، response.aiter_bytes() |
| Async generator | async 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 |
@asynccontextmanager | Async generator با یک yield | Lifespan، Fixture تست، Transaction |
contextlib.AsyncExitStack | مجموعهٔ پویای Context managerهای Async | بازکردن N Client در Lifespan |
contextlib.aclosing(agen) | بستن Generator در خروج بلوک | Generator دارای منبع، 3.10+ |
اصلاح / روش استفاده:
"""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.eventscontextvars میان 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 بگذارید |
| پارامتر صریح | کاربرد ندارد | بله | بله | بله |
اصلاح / روش استفاده:
"""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()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 کار را به حلقهٔ اصلی میسپارد.
| وضعیت | ابزار |
|---|---|
| ورودی اسکریپت / CLI | asyncio.run(main()) |
| چند اجرا روی یک حلقه، 3.11+ | with asyncio.Runner() as r: r.run(a()); r.run(b()) |
| حلقهٔ سفارشی uvloop | uvloop.run(main()) یا asyncio.run(main(), loop_factory=uvloop.new_event_loop) در 3.12+ |
| داخل Coroutine | await |
| از Thread دیگر به حلقهٔ فعال | asyncio.run_coroutine_threadsafe(coro, loop).result() |
| حلقه در Thread پسزمینه | loop.run_until_complete(...) / run_forever() در همان Thread |
| Jupyter / IPython | await سطح بالا؛ Kernel حلقه دارد؛ nest_asyncio فقط آخرین راه |
| کد Sync با یک فراخوانی Async | anyio.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 awaited | await جا افتاده یا بهجای تابع 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 seconds | Blocking یا 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 one | call_soon از Thread در Debug mode | call_soon_threadsafe |
اصلاح / روش استفاده: تست و سرور محلی را با PYTHONASYNCIODEBUG=1 یا python -X dev اجرا کنید؛ در تست بار loop.slow_callback_duration را به ۰٫۰۵ کاهش دهید و هر پیام بالا را باگ بدانید.
"""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 errClient ناهمگام 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=...) | 20 | Fan-out پایدار و زیاد به یک Host |
Limits(keepalive_expiry=...) | 5 s | Timeout بیکاری Load balancer کوتاهتر است |
Timeout(5.0) | 5 s برای هر مرحله | همیشه برای هر بالادست صریح تنظیم کنید |
Timeout(pool=...) | 5 s | Taskهای زیادی منتظر اتصال 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 def | Event loop | داخلی ندارد؛ Uvicorn --limit-concurrency | بله |
Route با def | AnyIO Worker Thread | 40 توکن مشترک | نه |
Dependency با async def | Event loop | ندارد | بله |
Dependency با def، شامل yield | AnyIO Worker Thread | 40 توکن | نه |
await run_in_threadpool(f) | AnyIO Worker Thread | 40 توکن | نه |
await asyncio.to_thread(f) | Executor پیشفرض asyncio | min(32, cpu + 4) | نه |
BackgroundTasks.add_task(def_fn) | AnyIO Worker Thread پس از پاسخ | 40 توکن | نه |
StreamingResponse(sync_iterator) | iterate_in_threadpool | 40 توکن | نه |
اصلاح / روش استفاده: وقتی همهٔ کارهای منتظر داخل تابع 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 با Portal | Lifespan را در 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 و Pool | async 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 / sqlite3 | def | نه؛ Thread pool | SQLAlchemy 2 و SQLModel |
SQLAlchemy Session در async def | async def | بله؛ باگ | همین صفحه |
AsyncSession با asyncpg / aiosqlite | async def | نه | SQLAlchemy 2 و SQLModel |
| asyncpg مستقیم | async def | نه | مستندات asyncpg |
| Motor / Beanie برای MongoDB | async def | نه | MongoDB با FastAPI |
redis.asyncio | async 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() | Selector | loop.add_reader(fd, callback) |
await to_thread(f) | Thread در Executor | loop.run_in_executor + call_soon_threadsafe |
task.cancel() | Task | پرچم میگذارد؛ قدم بعد CancelledError پرتاب میکند |
| پایان Task | Callbackهای Future | Taskهای منتظر بیدار میشوند |
متن دقیق خطا، هشدار و 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 بدون await | RuntimeWarning: coroutine 'forgotten' was never awaited + RuntimeWarning: Enable tracemalloc to get the object allocation traceback |
| همان در Debug mode | افزودن Coroutine created at (most recent call last) با پشته |
| Task شکستخورده بدون await | Task 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 mode | Executing <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 یک Coroutine | RuntimeError: cannot reuse already awaited coroutine |
asyncio.TaskGroup در 3.9 | AttributeError: module 'asyncio' has no attribute 'TaskGroup' |
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. |
put_nowait در صف پر | asyncio.QueueFull |
asyncio.TimeoutError is TimeoutError در 3.9 | False؛ از 3.11 نام مستعار |
کلاس پایهٔ CancelledError در 3.9 | BaseException |
| حلقهٔ پیشفرض macOS | _UnixSelectorEventLoop، slow_callback_duration: 0.1 |
Uvicorn --loop auto / asyncio / uvloop | uvloop.Loop / asyncio.unix_events._UnixSelectorEventLoop / uvloop.Loop؛ AnyIO در هرکدام tokens=40 |
نام Thread برای Route با def / run_in_threadpool | AnyIO worker thread |
| Executor پیشفرض روی 12 CPU | max_workers=16 |
| تست Async بدون Marker و افزونه، pytest 8.4.2 | async def functions are not natively supported. |
| گروه AnyIO با فرزند شکستخورده | ExceptionGroup از Backport بستهٔ exceptiongroup روی 3.9، شامل ValueError فرزند |
ماتریس نسخهها: چه چیزی کجا قابل استفاده است؟ مهم
| ویژگی | 3.9 | 3.10 | 3.11 | 3.12 | 3.13 | 3.14 | 3.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 |
اندازهٔ پیشفرض ThreadPoolExecutor | min(32, cpu_count + 4) | همان | همان | همان | process_cpu_count + 4 با سقف 32 | همان | همان |
حل مسائل رایج (Solving the classic problems)
| باگ | نشانه | اصلاح | هزینه |
|---|---|---|---|
| Client همگام HTTP در Route ناهمگام | کندی همهٔ Endpointها هنگام تأخیر بالادست؛ /health واقعی 0.554 s | httpx.AsyncClient از Lifespan یا Route با def | کم |
| time.sleep در Coroutine حلقه را میبندد | فاصلهٔ Heartbeat برابر 0.211 s | await asyncio.sleep | ندارد |
Driver همگام DB در async def | توان عملیاتی یک درخواست در هر لحظه | Driver Async یا Route با def و Pool | متوسط |
gather نامحدود روی فهرست بزرگ | اتمام سوکت، 429 بالادست، Pool timeout | Semaphore یا Worker pool روی Queue محدود | کم |
create_task و رهاکردن | کار گمشده، Task exception was never retrieved | Set قابل پیگیری / TaskGroup؛ صف برای کار پایدار | کم |
بلعیدن CancelledError | گیرکردن خاموشی و عملنکردن Timeout | پرتاب دوباره پس از پاکسازی | ندارد |
| نبود Timeout خروجی | انباشت درخواست هنگام اختلال | Timeout در Client و wait_for / timeout() | ندارد |
| شکست سریع gather با ادامهٔ همگروهی | کار بیهوده و اثر جانبی پس از خطا | TaskGroup / Task group در AnyIO | کم |
| CPU روی حلقه | جهش تأخیر، Debug "took 0.4 seconds" | ProcessPoolExecutor یا صف کار | متوسط |
| وضعیت درخواست در Thread-local | شناسهٔ درخواست اشتباه در Log | ContextVar | کم |
| خواندن-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)
| وضعیت | ابزار | تکنیک تکمیلی | دلیل |
|---|---|---|---|
| فراخوانی فراوان شبکه با کتابخانهٔ Async | Taskهای asyncio | Semaphore و Timeout | کمهزینهترین همروندی برای هر انتظار |
| همهٔ نتیجهها، شکست سریع و لغو بقیه | TaskGroup از 3.11+ / AnyIO | asyncio.timeout پیرامونی | Structured concurrency |
| شکست جزئی پذیرفتنی | gather(return_exceptions=True) | Log هر شکست | منبع خراب نباید کل صفحه را خراب کند |
| اولین پاسخ برنده است | wait(FIRST_COMPLETED) | لغو بازندهها | Hedged request |
| ارسال نتیجه بهمحض رسیدن | as_completed | لغو هنگام خروج زودهنگام | کاهش زمان اولین نتیجه |
| کتابخانه فقط Sync دارد | to_thread / Route با def | Executor مستقل برای وابستگی کند | آزادماندن حلقه |
| CPU از 10 ms تا چند ثانیه | ProcessPoolExecutor با run_in_executor | Semaphore روی ارسال کار | استفاده از هستهها و حلقهٔ آزاد |
| CPU طولانیتر یا نیاز به بقای Restart | صف Celery، arq، RQ، Dramatiq | کار بیاثر در تکرار (Idempotent) | پایداری و Retry |
| تولیدکننده سریعتر از مصرفکننده | Queue محدود | سیاست رد یا حذف | Back-pressure |
| وضعیت هر درخواست در پشتهٔ فراخوانی | ContextVar | reset در finally | درستی زیر همروندی |
| اجرای asyncio و Trio یا Structured concurrency روی 3.9/3.10 | AnyIO | @pytest.mark.anyio | یک API و Cancel scope |
| برنامهٔ Sync با یک فراخوانی Async | asyncio.run | ندارد | سادهترین پل |
| Notebook | await سطح بالا | nest_asyncio فقط در اجبار | حلقه از قبل فعال است |
چه وقت asyncio، Thread، Process یا Go؟
| نیاز | asyncio | Thread در CPython پیشفرض | Process | Go |
|---|---|---|---|---|
| 10,000 اتصال بیکار WebSocket یا SSE | بهترین | گران | بسیار گران | بهترین |
| Fan-out به 20 فراخوانی HTTP | 0.136 s واقعی | 0.133 s واقعی | بیشازحد سنگین | Goroutine |
| زیستبوم کتابخانه | باید Async باشد | هر کتابخانه | هر کتابخانه | کتابخانهٔ Go |
| CPU موازی | ندارد | برای Python خالص ندارد؛ GIL | بله | بله |
| ایمنی فراخوانی Blocking | یک فراخوانی همه را نگه میدارد | جدا برای هر Thread | جدا برای هر Process | Blocking طبیعی است |
| وضعیت مشترک | بین awaitها امن | قفل همهجا | اشتراک ندارد؛ IPC | Channel / Mutex |
| لغو | CancelledError و Scope | فقط پرچم مشارکتی | کشتن Process | context.Context |
| اشکالزدایی | Debug mode و مشاهدهٔ Task | پشتهٔ هر Thread | برای هر Process | Race 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 pool | Deadline 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 آنجا اجرا میشوند و انتظار موفقیت دارند.
۲. اندازهگیری مستقل 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 sn و 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
// 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 / Laravel | Python asyncio |
|---|---|
| Worker در PHP-FPM برای هر درخواست | Route با def در Thread / Worker در WSGI |
| Fiber از 8.1 | Coroutine، اما بدون علامتگذاری async/await |
| Event loop و Promise در ReactPHP | حلقهٔ asyncio و Future |
| Coroutine و Hook زمان اجرا در Swoole | Task در asyncio؛ Python کتابخانهٔ Async میخواهد؛ Hookها شبیه gevent هستند |
Swoole\Coroutine\Channel | asyncio.Queue |
Octane::concurrently([...])؛ Task worker در Process جدا در Swoole | run_in_executor(process_pool, ...) + gather |
| Worker بلندعمر Octane | Worker در Uvicorn با Lifespan |
Http::timeout(1) | httpx.Timeout(1.0) |
کار صفشده با dispatch(new Job) | صف کار Celery یا arq؛ نه create_task |
sleep() در Coroutine Swoole با Hook | await asyncio.sleep() |
Http::pool(fn (Pool $pool) => [...]) در Laravel | AsyncClient + 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: 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 asyncio | Go |
|---|---|---|
| واحد همروندی | Task؛ Coroutine روی یک حلقه | Goroutine؛ زمانبندی Runtime روی چند Thread |
| فراخوانی Blocking در Goroutine و Task | همهٔ Taskهای حلقه را متوقف میکند | فقط همان Goroutine را |
| CPU موازی | روی حلقه ندارد؛ Process لازم است | بله؛ GOMAXPROCS |
| Function colouring | async def باید await شود | ندارد |
| Channel در برابر Queue | asyncio.Queue(maxsize) | make(chan T, n) |
| Fan-out محدود | Semaphore + gather / TaskGroup | errgroup + SetLimit |
| لغو | task.cancel() → CancelledError در await بعدی | لغو context → بررسی ctx.Done() / ctx.Err() |
| مهلت | asyncio.timeout، wait_for | context.WithTimeout |
| کار نشتکرده | Task بدون ارجاع | Goroutine leak |
| مقدار هر درخواست | ContextVar | context.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 condition | Taskها در 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 و پرتاب دوباره |
| Shield | await 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 |
| اندازهٔ Pool | Executor پیشفرض min(32, cpu + 4)؛ AnyIO: 40 توکن؛ httpx: 100 اتصال و 20 Keep-alive |
| CPU | ProcessPoolExecutor با run_in_executor؛ ساخت یکباره |
| وضعیت درخواست | ContextVar؛ set → Token → reset در finally |
| Debug | PYTHONASYNCIODEBUG=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 نباشند |
| GIL | Thread برای 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 |
await | Coroutine جاری را تا پایان 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 برای بازگرداندن استثنا بهعنوان مقدار بهجای پرتاب اولین خطا |
TaskGroup | Context 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.timeout | Context 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 آن |
ThreadPoolExecutor | Thread pool در concurrent.futures؛ Executor پیشفرض حلقه |
ProcessPoolExecutor | Process 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 with | Context 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_asyncio | Patch ثالث برای 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 در Starlette | await 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 / Alembic | ORM با افزونهٔ asyncio، لایهٔ ORM با Pydantic و ابزار Migration |
| Uvicorn / Starlette / FastAPI | سرور ASGI، ابزار ASGI مبتنی بر AnyIO و Framework ساخت API |
منابع (References)
- Python docs, "asyncio — Asynchronous I/O": https://docs.python.org/3/library/asyncio.html
- Python docs, "Coroutines and Tasks": https://docs.python.org/3/library/asyncio-task.html
- Python docs, "Event Loop": https://docs.python.org/3/library/asyncio-eventloop.html
- Python docs, "Futures": https://docs.python.org/3/library/asyncio-future.html
- Python docs, "Queues": https://docs.python.org/3/library/asyncio-queue.html
- Python docs, "Synchronization Primitives": https://docs.python.org/3/library/asyncio-sync.html
- Python docs, "Streams": https://docs.python.org/3/library/asyncio-stream.html
- Python docs, "Subprocesses": https://docs.python.org/3/library/asyncio-subprocess.html
- Python docs, "Developing with asyncio": https://docs.python.org/3/library/asyncio-dev.html
- Python docs, "Exceptions" (asyncio): https://docs.python.org/3/library/asyncio-exceptions.html
- Python docs, "Runners": https://docs.python.org/3/library/asyncio-runner.html
- Python docs, "Platform Support": https://docs.python.org/3/library/asyncio-platforms.html
- Python docs, "Policies": https://docs.python.org/3/library/asyncio-policy.html
- Python docs, "Call Graph Introspection": https://docs.python.org/3/library/asyncio-graph.html
- Python docs, "concurrent.futures": https://docs.python.org/3/library/concurrent.futures.html
- Python docs, "contextvars": https://docs.python.org/3/library/contextvars.html
- Python docs, "contextlib": https://docs.python.org/3/library/contextlib.html
- Python docs, "threading": https://docs.python.org/3/library/threading.html
- Python docs, "multiprocessing": https://docs.python.org/3/library/multiprocessing.html
- Python docs, "selectors": https://docs.python.org/3/library/selectors.html
- Python docs, Glossary ("global interpreter lock"): https://docs.python.org/3/glossary.html
- Python docs, "Python support for free threading": https://docs.python.org/3/howto/free-threading-python.html
- Python docs, "Compound statements" (
async def,async for,async with): https://docs.python.org/3/reference/compound_stmts.html - Python 3.9 docs, "Coroutines and Tasks": https://docs.python.org/3.9/library/asyncio-task.html
- Python 3.9 docs, "Event Loop": https://docs.python.org/3.9/library/asyncio-eventloop.html
- What's New in Python 3.4: https://docs.python.org/3/whatsnew/3.4.html
- What's New in Python 3.5: https://docs.python.org/3/whatsnew/3.5.html
- What's New in Python 3.7: https://docs.python.org/3/whatsnew/3.7.html
- What's New in Python 3.8: https://docs.python.org/3/whatsnew/3.8.html
- What's New in Python 3.9: https://docs.python.org/3/whatsnew/3.9.html
- What's New in Python 3.11: https://docs.python.org/3/whatsnew/3.11.html
- What's New in Python 3.12: https://docs.python.org/3/whatsnew/3.12.html
- What's New in Python 3.13: https://docs.python.org/3/whatsnew/3.13.html
- What's New in Python 3.14: https://docs.python.org/3/whatsnew/3.14.html
- What's New in Python 3.15: https://docs.python.org/3/whatsnew/3.15.html
- PEP 342, "Coroutines via Enhanced Generators": https://peps.python.org/pep-0342/
- PEP 380, "Syntax for Delegating to a Subgenerator": https://peps.python.org/pep-0380/
- PEP 3156, "Asynchronous IO Support Rebooted: the asyncio Module": https://peps.python.org/pep-3156/
- PEP 492, "Coroutines with async and await syntax": https://peps.python.org/pep-0492/
- PEP 525, "Asynchronous Generators": https://peps.python.org/pep-0525/
- PEP 530, "Asynchronous Comprehensions": https://peps.python.org/pep-0530/
- PEP 567, "Context Variables": https://peps.python.org/pep-0567/
- PEP 654, "Exception Groups and except*": https://peps.python.org/pep-0654/
- PEP 703, "Making the Global Interpreter Lock Optional in CPython": https://peps.python.org/pep-0703/
- PEP 779, "Criteria for supported status for free-threaded Python": https://peps.python.org/pep-0779/
- PEP 537 / 569 / 596 / 664 / 745 / 790 (3.7 / 3.8 / 3.9 / 3.11 / 3.14 / 3.15 release schedules): https://peps.python.org/pep-0537/, https://peps.python.org/pep-0569/, https://peps.python.org/pep-0596/, https://peps.python.org/pep-0664/, https://peps.python.org/pep-0745/, https://peps.python.org/pep-0790/
- CPython 3.9 source,
Lib/asyncio/base_events.py: https://raw.githubusercontent.com/python/cpython/3.9/Lib/asyncio/base_events.py - CPython 3.9 source,
Lib/asyncio/tasks.py: https://raw.githubusercontent.com/python/cpython/3.9/Lib/asyncio/tasks.py - CPython 3.9 source,
Lib/asyncio/threads.py: https://raw.githubusercontent.com/python/cpython/3.9/Lib/asyncio/threads.py - CPython 3.9 source,
Lib/asyncio/locks.py: https://raw.githubusercontent.com/python/cpython/3.9/Lib/asyncio/locks.py - CPython source,
Lib/concurrent/futures/thread.py(3.9 and main): https://raw.githubusercontent.com/python/cpython/3.9/Lib/concurrent/futures/thread.py, https://raw.githubusercontent.com/python/cpython/main/Lib/concurrent/futures/thread.py - AnyIO, "Creating and managing tasks": https://anyio.readthedocs.io/en/stable/tasks.html
- AnyIO, "Cancellation and timeouts": https://anyio.readthedocs.io/en/stable/cancellation.html
- AnyIO, "Using synchronization primitives": https://anyio.readthedocs.io/en/stable/synchronization.html
- AnyIO, "Working with threads": https://anyio.readthedocs.io/en/stable/threads.html
- AnyIO, "Testing with AnyIO": https://anyio.readthedocs.io/en/stable/testing.html
- AnyIO, "Why you should be using AnyIO APIs instead of asyncio APIs": https://anyio.readthedocs.io/en/stable/why.html
- uvloop README: https://raw.githubusercontent.com/MagicStack/uvloop/master/README.rst
- httpx, "Async Support": https://www.python-httpx.org/async/
- httpx, "Resource Limits": https://www.python-httpx.org/advanced/resource-limits/
- httpx, "Timeouts": https://www.python-httpx.org/advanced/timeouts/
- httpx, "Clients": https://www.python-httpx.org/advanced/clients/
- FastAPI, "Concurrency and async / await": https://fastapi.tiangolo.com/async/
- FastAPI, "Lifespan Events": https://fastapi.tiangolo.com/advanced/events/
- FastAPI, "Async Tests": https://fastapi.tiangolo.com/advanced/async-tests/
- FastAPI, "Dependencies with yield": https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/
- Starlette, "Thread Pool": https://www.starlette.dev/threadpool/
- Starlette source,
starlette/concurrency.py: https://raw.githubusercontent.com/encode/starlette/master/starlette/concurrency.py - Uvicorn, "Settings": https://www.uvicorn.dev/settings/
- pytest-asyncio documentation: https://pytest-asyncio.readthedocs.io/en/latest/
- pytest-asyncio, "Concepts": https://pytest-asyncio.readthedocs.io/en/latest/concepts.html
- pytest-asyncio, "Configuration": https://pytest-asyncio.readthedocs.io/en/latest/reference/configuration.html
- SQLAlchemy 2.0, "Asynchronous I/O (asyncio)": https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html
- nest_asyncio README: https://raw.githubusercontent.com/erdewit/nest_asyncio/master/README.rst
- PyPI JSON for pins (pytest-asyncio, anyio, uvloop): https://pypi.org/pypi/pytest-asyncio/json, https://pypi.org/pypi/anyio/json, https://pypi.org/pypi/uvloop/json
- A Tour of Go, "Concurrency" (source): https://raw.githubusercontent.com/golang/website/master/_content/tour/concurrency.article
- Go blog, "Go Concurrency Patterns: Pipelines and cancellation" (source): https://raw.githubusercontent.com/golang/website/master/_content/blog/pipelines.md
- Effective Go: https://go.dev/doc/effective_go
- The Go Memory Model: https://go.dev/ref/mem
- PHP manual, "Fibers": https://www.php.net/manual/en/language.fibers.php
- ReactPHP: https://reactphp.org/
- Swoole README: https://raw.githubusercontent.com/swoole/swoole-src/master/README.md
- Open Swoole, "Coroutine": https://openswoole.com/docs/modules/swoole-coroutine
- Laravel 13, "Octane": https://laravel.com/docs/13.x/octane
- Laravel 13, "HTTP Client" (concurrent requests,
Http::pool): https://laravel.com/docs/13.x/http-client