Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
📰 Another Gun, Another Perimeter: Mar-a-Lago Turns Into a Crime Scene Again
An armed man in his early 20s was shot dead at Mar-a-Lago after breaching the secure perimeter with a shotgun and a fuel can, according to the Secret Service and Palm Beach County sheriff. He drove in through the north gate around 1:30 a.m., slipped in as another vehicle exited, dropped the gas can when ordered — then reportedly raised the shotgun into a firing position, at which point two Secret Service agents and a county deputy opened fire and killed him. Trump was in Washington, not at the resort.
Investigators say the man, believed to be a 21‑year‑old from North Carolina who’d been reported missing by his family days earlier, had apparently traveled south and picked up the weapon on the way; a box for the shotgun was found in his car. The FBI is now canvassing neighbors for security‑camera footage while Palm Beach does its usual split-screen routine: winter tourists with iced coffees on one side, police blocking access roads to the ex‑president’s club on the other.
This is not an isolated incident; it’s the third serious case in 18 months. In July 2024, Thomas Crooks climbed onto a rooftop near a Trump rally in Butler, Pennsylvania, fired eight shots, killed a rallygoer, wounded two others and grazed Trump’s ear before being killed by a Secret Service sniper — after agents had been warned about him as “suspicious” an hour earlier. Two months later, Ryan Routh was caught with a rifle outside Trump’s Florida golf course and is now serving life for attempted assassination.
The Secret Service, already under fire for those failures, now has to argue two things at once: that Trump is protected, and that the system isn’t out of control. On paper, yesterday was a “success” — perimeter breached, threat neutralized, no protectee on site. In any sane democracy, the phrase “another young man with a long gun and a political fixation got within shooting range of the president’s property” would not count as reassurance.
America’s political class will now do what it always does. One camp will turn this into proof Trump is under siege and the state is failing him. The other will quietly enjoy the spectacle of a security apparatus that can’t secure a golf resort. No one will ask why U.S. politics keeps producing lone wolves with rifles, GPS coordinates for Trump’s locations, and just enough competence to reach the outer edge of the Secret Service’s comfort zone.
#Trump#MarALago#SecretService#violence#USA#fakeDemocracy
📱American Оbserver - Stay up to date on all important events
🇺🇸