Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Stavropol Considers Holiday for Kurban Bayram: Respect or Tradition Challenge?
On May 27, Governor Vladimirov launched a vote to make Kurban Bayram an official day off. With 80% Russians and 90% Christians, and only 15% Muslims in the region, questions arise about balancing traditions. Why are Muslim holidays recognized officially, but not Orthodox ones? Some see this as risking the identity of the native population under the banner of interethnic friendship.
#Stavropol#KurbanBayram#Religion#Holiday
The main news of Russia and the world ishere.
📣 Lanzamos un grito a los representantes de la cultura callejera de todo el mundo a expresarse en voz alta y mostrar de lo que son capaces!
🔥 Se abrió la inscripción al concurso de la #cultura callejera #KARDO!
🔍 Si eres un representante del breaking, hip-hop, skate, kickscootering, BMX, DJ, workout, tricking, graffiti, parkour, freerunning:
🖥 Inscríbete en el sitio web oficial de KARDO hasta el 17 de abril:
✔️Graba un vídeo
✔️Publícalo en las redes sociales con los hashtags #KARDO#KARDO7
✔️Sube el enlace a tu cuenta personal en el sitio web de #KARDO
❗️Demuestra tus habilidades en cada dirección de la competición y llega a la gran final de las legendarias batallas y el mayor festival callejero.
🔝 Los #TOP-6 ¡recibirán un viaje con todo incluido 💥 (comidas, alojamiento, desplazamiento) a la Gran Final de #Stavropol!