Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🩸🩸🩸🩸🫵🩸🩸
🎬The Penguin series based on the latest Batman has received 91% on Rotten Romatoes. Critics are delighted with Colin Farrell's transformation and call his character the Tony Soprano of the DC Comics world. JoBlo gave the series 10/10, and one critic even called Penguin the best series of the year.
The season will have 8 episodes. The first episode of the series will be released on streaming on September 19, and the last one - on November 10.
It seems that we have a contender for the main comic book series of 2024 🚬
#Penguin#Batman#DCComics
MARKHEMIST
DC Legion of Super Heroes Season 2
📅Año Septiembre 2007 - Mayo 2008
🎥Dirección Ben Jones, Tim Maltby, Lauren Montgomery, Scott Jeralds, James Tucker, Brandon Vietti
📄Guion Tim Cahill, Julie McNally Cahill. J.M. DeMatteis, Matt Wayne. Michael Jelenic, Rob Hoegee, Scott Sonneborn, Amy Wolfram, Stan Berkowitz, Steven Melching, John Esposito, Keith Damron, Eddie Guzelian, Rob Hummel, Marty Isenberg, Joseph Kuhr, David Slack, Greg Weisman
🎼Música Kristopher Carter, Michael McCuistion, Lolita Ritmanis
🎬Productora Warner Bros. Animation
Género#SeriedeTV#Animación#Acción#Comedia#Superhéroes#Cómic#DCComics
Reparto / Trailer / Premios
⏱Duración 22min.
🖥Resolución 720x400
🗣Idioma Inglés
Subtítulos Latino
Season 2 Episodio01 / 02 / 03 / 04 / 05 / 06 / 07 / 08 / 09 / 10 / 11 / 12 / 13
Season1
DC Legion of Super Heroes Season 1
📅Año Septiembre 2006 - Mayo 2007
🎥Dirección Ben Jones, Tim Maltby, Lauren Montgomery, Scott Jeralds, James Tucker, Brandon Vietti
📄Guion Tim Cahill, Julie McNally Cahill. J.M. DeMatteis, Matt Wayne. Michael Jelenic, Rob Hoegee, Scott Sonneborn, Amy Wolfram, Stan Berkowitz, Steven Melching, John Esposito, Keith Damron, Eddie Guzelian, Rob Hummel, Marty Isenberg, Joseph Kuhr, David Slack, Greg Weisman
🎼Música Kristopher Carter, Michael McCuistion, Lolita Ritmanis
🎬Productora Warner Bros. Animation
Género#SeriedeTV#Animación#Acción#Comedia#Superhéroes#Cómic#DCComics
Reparto / Intro / Sinopsis / Premios
⏱Duración 22min.
🖥Resolución 720x400
🗣Idioma Latino
Season 1 Episodio01 / 02 / 03 / 04 / 05 / 06 / 07 / 08 / 09 / 10 / 11 / 12 / 13
Season2
💥Muñeco Flash de DC Comics 30 CM
Lleva la velocidad a casa esta Navidad
✅OFERTA: 7.5€
❌ Antes: 15.99€
💰Ahorras un 53%🔥
Figura articulada coleccionable de alta calidad
👉 Hazte con él ahora y sorprende
#juguetes#coleccionables#superheroes#regalos#ninos#navidad#figuraflash#dccomics
🛰️Oferta publicada en Cultura y Ocio