Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Thiago Alcántara ha decidido retirarse del fútbol profesional.
El exjugador de Barça, Bayern, Liverpool y España ha tomado su decisión.
La pasión y el amor de Thiago por el juego continúan mientras está listo para un nuevo capítulo en el fútbol después de algunos meses de planificación.
📱: Fabrizio Romano
@Fut_Planet⚜️#Thiago⚽️
Lara, speaking from Brazil, has had no contact with her husband, Thiago Ávila, since he was abducted and detained illegally by Israeli forces from the 'Madleen'. Since then, Thiago has been placed in solitary confinement, denied communication with his family.
According to Lara, Israeli authorities threatened Thiago with the psychological torment of isolation without light or ventilation. Despite this, Thiago remains on hunger strike, holding firm to his belief in justice for Palestinians and the right of every child to food, safety, and freedom.
From his prison cell, he wrote a letter to his 1-year-old daughter. Lara generously shares that with us today.
This is a call not just for Thiago’s release—but for the world to pay attention to Gaza, to Palestine, and to all people who are exploited, forced to live under occupation.
#FreedomFlotilla#Madleen#Thiago#IOF#WeWillSail#BreakIsraelsSiege#EndTheBlockade
"Families of Gaza are not less important than my family. It’s by mere chance that we are not one of those families that are in Gaza right now."
Thiago Ávila, father and activist aboard 'Handala', will sail towards Gaza with an urgent mission: to break the illegal siege and stand with the children of Gaza. 'Handala' is a small boat, but it carries the weight of a global uprising for justice. As catastrophic famine unfolds across Gaza, evidence of heinous sexual and physical violence by the IOF continues to emerge, and the Israeli and U.S.-backed genocide persists with impunity, people power is more integral than ever—it’s up to us to shape a new society.
The world must not turn its eyes away. Keep your eyes on 'Handala'. Share our mission, amplify Palestinian voices, and do everything you can to stand for Gaza. The flood of change is coming—be part of it. #FreedomFlotilla#Handala#FreePalestine#Gaza#AllEyesOnDeck#FreeGaza#WeWillSail#Thiago#Brazil#HumanRights#Genocide#IOF