Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🇽🇰#Kosovo: Kosovo Police has found yet another cache of weapons, ammunition, and military gear yesterday, after searching the basement of a residential building on Vasilije Ostroški Street in North Mitrovica.
Officers recovered multiple assault rifles, hundreds of rounds of ammunition, magazines, a smoke grenade, body armor, and various pieces of military clothing and equipment. No arrests were made, and an investigation into illegal weapons possession is ongoing.
This comes as, over the past week, several abandoned weapons caches have been discovered in the north, including one containing hundreds of kilograms of explosives and a practice anti-tank mine. It remains unclear whether the stashes are linked to a specific paramilitary group or a criminal organization.
(📸 via @KosovoPolice on FB)
🇽🇰#Kosovo: Kosovo Police have uncovered weapons, ammunition, and explosives in abandoned houses in Zubin Potok, Zvečan, and the North Mitrovica area since the start of this week.
Just in North Mitrovica, authorities seized around 140 kg of explosives, which they say were produced in Serbia.
The latest seizure was yesterday in Mitrovicë Veri, where police, acting on information from citizens, found several illegal weapons, ammunition, and a VPMA-2 (a practice version of the PMA-2 anti-personnel mine).
(📸 via @Kosovo_police on X)
#Kosovo
L’Assemblea della Repubblica del Kosovo ha adottato un progetto di legge finalizzato alla regolamentazione giuridica del diritto alla riproduzione sessuale e della procreazione medicalmente assistita.
@OsservatorioEsteri
#Kosovo🇽🇰
#Parlamentari
🕖Ore 19:00.
Affluenza parziale: 44,29%
N.B.: nel computo mancano i seggi speciali, quelli allestiti all'estero e alcune sezioni allestite nel Paese, che non hanno ancora comunicato i dati.
@TuttoElezioni
#Kosovo#primario Huelga en la mina Trepca https://www.aa.com.tr/en/europe/kosovo-mine-workers-begin-hunger-strike-for-better-working-conditions/3032646
‼️A la chita callando, #España pasa a reconocer la independencia de #Kosovo. Un nuevo giro de 180º de Sánchez alinéandose con #EEUU que impulsa la #guerra
https://www.euractiv.com/section/enlargement-neighbourhood/news/kosovo-says-spain-recognises-its-passports/
#Kosovo#NATO
Il governo del Kosovo ha chiesto agli Stati Uniti una base permanente sul suo territorio ed ha chiesto di entrare nella NATO.
@UltimoraPolitics
#Kosovo
Il Presidente del Kosovo Hashim #Thaçi si è dimesso dopo che è stata confermata l'accusa di crimini di guerra e crimini contro l'umanità dalla Procura dell'Aia.
@NewsDalMondoo