Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🔖 How Ukraine’s killer drones are beating Russian jamming | Hacker News #pinboard#warfare
As an engineer, I am fascinated by it all. As a human, I am horrified that we democratized violence on this scale.
A missile worth perhaps a million dollars can kill maybe 12 or 20 people. But for one million dollars, you can buy 10,000 drones, put four grenades on each, and they will kill 1,000 or even 2,000 people or destroy 200 tanks.
https://news.ycombinator.com/item?id=44168658
🚨🇺🇸TRUMP: IRANIAN OPERATIONS WILL END "VERY SOON" BUT NOT THIS WEEK
🔹 11 days of military action have dismantled Iran's radar, telecommunications, leadership, missile stockpiles, and navy 💥
🔹 US forces destroyed 10 Iranian mine-laying vessels in Strait of Hormuz yesterday — key route for 20% of global oil 🛢️
🔹 Defense Secretary Hegseth calls March 10 "most intense" day of bombardment — 140 US troops wounded, 7 killed ⚰️
🔹 President warns "death, fire, and fury" if Tehran disrupts shipping lanes — tensions escalating 🔥
The Commander-in-Chief knows exactly what he's doing 😤💪
#USNews#MiddleEast#warfare
@america
🌎 Ancient Greek fire, known as "Greek fire," was a weapon that could burn even on water. This flammable liquid, projected from tubes, terrified enemies at sea and kept its formula a closely guarded secret, lost to history. ✨
#history⚡#chemistry⚡#warfare
👉subscribe Interesting Planet
📢 Ukraine's defense forces resort to using Leopard tanks as long-range artillery, failing to fulfill their intended purpose against Russia. The highly anticipated offensive has turned into a defensive strategy, with the giant tanks deployed along the front line. But will this change the course of the conflict? Meanwhile, Poland plans to provide Ukraine with additional armored firepower. The war continues... 💥#Ukraine#Russia#LeopardTanks#Warfare
https://www.gazeta.ru/army/news/2023/12/05/21855127.shtml
Subscribe to @BadVolfNews