Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Venezuelan President Nicolás Maduro said authorities had neutralized a “fascist outbreak” following last Sunday's elections.
Check out a gallery of yesterday's rallies: https://venezuelanalysis.com/images/venezuela-government-opposition-supporters-take-to-the-streets-in-post-electoral-scene/
#Venezuela#Elections2024#Demonstration
#Ethiopia: Tigray education community plans #protest over budget cuts threatening schools
Teachers and students in #Tigray are preparing to stage a peaceful #demonstration protesting new budget restrictions they say are pushing the region’s already fragile education system toward collapse.
Kiros Guesh, Head of the Tigray Education Bureau, told Addis Standard that the planned protest aims to condemn what he described as an “unlawful budget ban” and to call for urgent intervention to prevent further disruption to schooling.
A pretest demonstration is scheduled for Tuesday, March 24, 2026, with organizers expected to announce further details in an official press release.
The protest comes as the region’s education sector continues to face mounting challenges linked to a deepening financial crisis.
In its letter addressed to Ministry of Education, the #Ethiopia Disaster Risk Management Commission, and other education partners, the Tigray Education Bureau.......
Read more: https://addisstandard.com/?p=56003
«Последняя демонстрация динозавров-вегетарианцев за минуту до вымирания», digital art by Doping Pong, 2018-2024
Этот скетч был сделан в 2018 году, когда арт-группа Doping Pong сотрудничала с компанией Vibеr над креативными разработками вошедших в моду стикерпаков для мессенджера. Так появились эти три персонажа, травоядные динозавры: Диплодок, Стегозавр и Трицератопс.
Дальше эскиза дело не пошло, но сейчас, во время мировых катаклизмов, захотелось его вспомнить.
Этот месседж динозавров-вегетарианцев, адресованный плотоядным братьям и сестрам, актуален как никогда.
#dopingpong#динозавры#вегетарианцы#последняя#демонстрация
#dinosaurs#vegetarians#last#demonstration#givepeaceachance