Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
from fastapi.concurrency import run_in_threadpool
async def execute(data: DataRequest) -> DataResponse:
try:
result = await run_in_threadpool(sync_function, data)
return DataResponse(data=result)
except Exception as e:
return DataResponse(
error=str(e),
success=False,
)
В общем работает нормально. Для всех вызовов под капотом используется общий тредпул, всё работает предсказуемо.
Но потребовалось изменить количество запускаемых в пуле потоков (по умолчанию создается 40 воркеров).
Так как дело происходит с FastAPI, делается это через lifespan используя настройки anyio:
import anyio
@asynccontextmanager
async def lifespan(app: FastAPI):
limiter = anyio.to_thread.current_default_thread_limiter()
limiter.total_tokens = 100
yield
# если вдруг нужно вернуть обратно
limiter.total_tokens = 40
Зачем менять количество воркеров?
- уменьшить, если оперативки мало (один тред занимает ~8мб)
- увеличить чтобы выдержать нагрузку
Если есть предложения получше при тех же вводных - предлагайте😉
#async
A very happy International Women's Day to all from the Russian Foreign Ministry!
Dear women, colleagues, loved ones and family — we wish you all the best ❤️
May you enjoy happiness and good health 💐
#IWD2024
Happy #InternationalWomensDay
We recognise all women actively contributing to the strengthening of Nigeria's health security!
We appreciate all women whose resilience and expertise drive positive change and accelerate progress in making our communities healthier, stronger, and more vibrant.
#IWD2024
📌 Did you know that you can use the IRAS Relief Checker to find out more about the tax reliefs and/or rebates you may be qualified for?
Meet working mum Boon Hui, who is no stranger to the hectic, fast-paced life of the media industry. She’s thankful that despite the demanding schedule, her parents can help manage her teenage boys while she’s at work.
She’s also appreciative of the tax reliefs and rebates which have considerably lightened the family’s financial load.
This #internationalwomensday, we’d like to honour the strong women, families, friends and allies in our lives – for the seen and unseen labour they’ve carried at home and at work to help make our lives a little lighter. ❤
#iwd2024
🙋🏻♀️ Huquqlari himoyalangan va imkoniyatlarga ega ayollar O‘zbekiston🇺🇿 farovonligining asosidir!
8️⃣ Xalqaro xotin-qizlar bayrami muborak bo'lsin!
#WomensDay#IWD2024#8mart
🎉 Xalqaro xotin-qizlar kuniga tayyormisiz?
🤔 Qani, erkak kishini ilhomlantirib, hayoti va ishini yaxshilashga qodir ayol kimligini bilaylikchi!
✅ Bugun savolimizga Diyor Mirzaahmedov, O'zbekiston marketing assotsiatsiyasi raisining javobini e’tiboringizga taqdim etamiz.
—
#WomensDay#InspireInclusion#InvestInWomen#IWD2024