Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🌐 Astăzi, 24 octombrie, este celebrată Ziua Națiunilor Unite 🇺🇳.
🤝 Biroul Național de Statistică adresează sincere felicitări organizațiilor ONU Moldova și mulțumiri pentru că ne sunt alături și ne oferă suport continuu în vederea consolidării capacităților sistemului statistic național și modernizării producției și diseminării datelor statistice de calitate, în corespundere cu standardele internaționale.
#ZiuaONU#UNDay
🇰🇬🇺🇳 Кыргыз Республикасы эл аралык коомчулук менен катар БУУнун күнүн белгиледи
🇰🇬🇺🇳 Кыргызская Республика присоединяется к мировому сообществу в праздновании Дня Организации Объединенных Наций
🇰🇬🇺🇳 The Kyrgyz Republic joins the international community in celebrating United Nations Day
#UNDay#UN#UnitedNations#ООН
🔗 Толугураак / Подробнее: mfa.gov.kg
LinkedIn | Instagram | X (Twitter) | Facebook | YouTube
☀️ “Ziyo Forum” yoshlar markazida BMT kuni munosabati bilan “Youth United for the UN Day: Empowering Sustainable Future” sessiyasi bo‘lib o‘tdi!
🇺🇳27-oktabr kuni “Ziyo Forum” yoshlar markazida yoshlar uchun ilhomlantiruvchi sessiya tashkil etildi. Tadbir davomida Alisher Asrorov— UNODC Youth Network Leader in Uzbekistan, Webster Universitetining Career & Business Development menejeri va sobiq BMT Yoshlar Kengashi raisi — BMTning O‘zbekistondagi faoliyati, Barqaror Rivojlanish Maqsadlari (SDGs) hamda yoshlarning global tashabbuslardagi o‘rni haqida o‘z tajribasi asosida so‘zlab berdi.
📌Ishtirokchilar ochiq muloqotda faol qatnashib, “Kahoot” viktorinasida o‘z bilimlarini sinovdan o‘tkazishdi. Tadbir yakunida eng faol yoshlarga maxsus sovg‘alar topshirildi va umumiy suratga tushildi.
🌍Sessiya iliq va ilhomlantiruvchi muhitda o‘tib, yoshlarni global fikrlash va barqaror kelajak sari ilhomlantirdi.
📸 Barcha suratlarni quyidagi havola orqali ko‘rishingiz mumkin:
👉https://disk.yandex.ru/d/1A8GU1Uc6bujhg
☀️ “Youth United for the UN Day: Empowering Sustainable Future” session was successfully held at Ziyo Forum Youth Center!
🇺🇳On October 27, a special and inspiring session took place at the Ziyo Forum Youth Center. Alisher Asrorov— UNODC Youth Network Leader in Uzbekistan, Career & Business Development Manager at Webster University, and former Chair of the UN Youth Advisory Board — shared his insights on the UN’s role in Uzbekistan, the Sustainable Development Goals (SDGs), and the importance of youth participation in global initiatives.
📌Participants actively engaged in open discussions and tested their knowledge through the interactive Kahoot quiz. The most active attendees received special gifts, and the event concluded with a group photo.
🌍The session took place in a warm and inspiring atmosphere, motivating young people to think globally and contribute to a sustainable future.
📸 Check out all the event photos at the link below:
👉https://disk.yandex.ru/d/1A8GU1Uc6bujhg
#ZiyoForum#UNDay#YouthEmpowerment#SustainableFuture#UNUzbekistan#SDGs#YouthCenter