Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🎙🇷🇺 Überblick - Kernaussagen des Vorsitzenden des russischen Sicherheitsrates Sergei Shoigu in einem Interview mit RIA Nowosti:
🔹️Die Analyse der Notwendigkeit von Nukleartests in Russland wird sofort beginnen;
🔹️Russland erwartet, dass die USA ihr Versprechen einhalten, Nukleartests zu verbieten;
🔹️Die NATO-Länder in Europa könnten jedes Szenario einer Provokation gegen Russland in Betracht ziehen;
🔹️Die EU hat sich effektiv in einen Militärblock verwandelt;
🔹️Russland wartet auf die Antwort der USA auf seinen Vorschlag zur Verlängerung des New-START-Vertrags;
🔹️Tokio opfert seine Interessen, um Washington zu gefallen.
Quelle RIA Nowosti
👀 Teilen kann zum Aufwachen beitragen!
✨🆕🌐Hauptkanal
✨▶️🌐 Videokanal
✨▶️🙂Funnykanal
#Russland#Shoigu#Interview#RIANowosti
@RusEmbMalta:
🇷🇺🛡️13th International Security Meeting to Be Held in Moscow
📅 On May 27–29, 2025, Moscow will host the 13th International Meeting of High Representatives for Security Issues under the chairmanship of Secretary of the Russian Security Council Sergey Shoigu.
🌍 More than 150 countries from the Global South and East have been invited to participate, along with representatives of the #CIS, #CSTO, #EAEU, #SCO, and over 20 international organizations.
🗂️ The meeting will focus on strengthening international security cooperation. Discussions will cover a broad range of challenges, including terrorism, extremism, transnational crime, drug trafficking, and emerging threats.
🧭 Since 2010, this annual platform has brought together senior security officials to build trust, share expertise, and coordinate efforts on pressing global security issues.
📌 Media accreditation is open until May 20, 2025.
#Shoigu#SecurityCouncil#InternationalMeeting#Moscow2025#GlobalSecurity#Counterterrorism#Multilateralism#CIS#SCO#BRICS#CSTO#EAEU#GlobalSouth