Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🌍 Remote sensing satellites can now detect wildfire smoke plumes traveling thousands of kilometers. These space-based observations help track air quality and protect health far beyond fire zones. ✨
#remote⚡#sensing⚡#satellites⚡#airquality⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
⏸A powerful video by our students raising awareness about the dangers of air pollution.
#AirQuality#Sustainability#EcoEducation#GreenUniversity#ActNow
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
Co-creation Workshop on Climate and Air Quality
💬On December 4, Green University, together with Clean Air Asia and with the support from MOEJ, hosted a workshop in Tashkent focused on developing projects to improve air quality and reduce emissions. The workshop highlighted the JCM, project idea development, and knowledge exchange with international experts.
The workshop:
⚪️Helped to explore the co-benefits of clean air and climate mitigation
🔵Introduced the Joint Crediting Mechanism (JCM) as a financing tool for low-carbon projects
🔴Developed Project Idea Notes (PINs) with city officials and experts
🟢Facilitated knowledge exchange with specialists from Japan and Asia
#GreenUniversity#AirQuality#ClimateAction#SustainableCities#CleanAirAsia#JCM#Uzbekistan#EnvironmentalLeadership
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
Air Quality Assessment in Termez 2025: Toward Cleaner Air and Clearer Skies
🔴On December 16, 2025, Green University, together with UNEP and the Finnish Meteorological Institute, presented the results of the air quality assessment in Termez. The event brought together government representatives, experts, development partners, media, and civil society.
🔴The assessment, conducted at the request of the National Committee on Ecology and Climate Change of Uzbekistan, was based on data from the first automatic reference air monitoring station installed in Termez in 2024 with the support of the Zamin Foundation. The study identified key pollution sources and provided science-based recommendations to improve air quality.
🔴The discussion also covered new air quality management strategies, including the work of Uzhydromet and youth-focused environmental initiatives by the Zamin Foundation.
#AirQuality#CleanAir#Termez#Uzbekistan#GreenUniversity#UNEP#FMI#ClimateAction#EnvironmentalProtection
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube