Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Every parent needs to listen to this life-changing tip from PM Modi! Let your children make their choices in life & make their own path
👉 To listen to more mantras of success, Don't forget to watch #PPC2023 on 27th Jan 2023
https://youtu.be/Fwdx_cBqiDU
Every parent needs to listen to this life-changing tip from PM Modi! Let your children make their choices in life & make their own path
👉 To listen to more mantras of success, Don't forget to watch #PPC2023 on 27th Jan 2023
https://youtu.be/Fwdx_cBqiDU
परीक्षा से पहले की तैयारियों को लेकर अब बिल्कुल न हो परेशान; क्योंकि प्यारे बच्चों जल्द आ रहा है प्रधानमंत्री के साथ परीक्षा पे चर्चा 2023 संवाद।
#PPC2023
https://youtu.be/SKmrRc2-QTQ
अपने पैशन को चुनें या एक अच्छे करियर की प्लानिंग करें?
करियर या परीक्षा से जुड़े आपके सभी सवालों के पीएम 27 जनवरी 2023 को देंगे जवाब। #PPC2023
https://youtu.be/RzB7PY4VX0w
विजिट करें: mygov.in/ppc-2023/
परीक्षा से डरने के बजाय मुस्कुराते हुए उसे अपना बनाएं।
27 जनवरी, 2023 को #PPC2023 में प्रधानमंत्री के टिप्स से परीक्षा या करियर से जुड़े आपके हर सवाल का मिलेगा समाधान।
#PPC2023
👆Wondering how to create a perfect balance of studies and sports for your children during exams? PM Modi is here to help
Participate in #PPC2023 and get tips on dealing with your children's exam stress!
Visit: innovateindia.mygov.in/ppc-2023/
👆Become the best coach, mentor and teacher of your children with the help of PM's tips and advice!
Participate in #PPC2023 and make your children exam ready
Visit: https://innovateindia.mygov.in/ppc-2023/
परीक्षा के मुश्किल दिनों को बनाएं खुशनुमा और तनावमुक्त। परीक्षा पे चर्चा 2023 में शामिल होने के लिए भेजें अपने सुझाव और सवाल, आपको मिल सकता है प्रधानमंत्री से सीधे संवाद का मौका।
#PPC2023
https://youtu.be/YcV_uea2ok8
👆Become the best coach, mentor and teacher of your children with the help of PM's tips and advice!
Participate in #PPC2023 and make your children exam ready
Visit: https://innovateindia.mygov.in/ppc-2023/
👆Help your children reach their maximum potential this exam season, with PM Modi's inspiring advice!
👉 Participate in #PPC2023 and make your children exam ready.
Visit: https://innovateindia.mygov.in/ppc-2023/
👆Become the best coach, mentor and teacher of your children with the help of PM's tips and advice!
Participate in #PPC2023 and make your children exam ready
Visit: https://innovateindia.mygov.in/ppc-2023/