Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🌍 The Mongolian steppes have supported nomadic herding for centuries, with grasslands shaped by grazing animals and seasonal movement. This partnership keeps both wildlife and pastures thriving naturally. ✨
#nature⚡#society⚡#grasslands⚡#geography⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Temperate grasslands like the Eurasian steppes can experience temperature swings of over 40°C between summer and winter, creating some of the planet’s most extreme seasonal contrasts. ✨
#grasslands⚡#savanna⚡#climate⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Pampas grasslands in South America are so fertile they support one of the world’s largest cattle industries and can produce up to seven harvests of grass each year, fueling global food markets. ✨
#grasslands⚡#agriculture⚡#SouthAmerica⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Africa’s Miombo savanna covers over 2.7 million square kilometers—about the size of Argentina. Its woodlands support hundreds of unique butterfly species found nowhere else on Earth. ✨
#savanna⚡#grasslands⚡#ecosystems⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some grassland plants grow deep roots reaching over 2 meters underground. These roots help the plants survive drought and anchor soil, making grasslands some of the most erosion-resistant landscapes. ✨
#grasslands⚡#savanna⚡#ecology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Grasslands cover about 40% of Earth’s land surface and are found on every continent except Antarctica. Some of the world’s richest soils, called mollisols, form in temperate grasslands. ✨
#grasslands⚡#savanna⚡#soil⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Some grassland soils are so fertile they can support crops for decades without added fertilizer. These deep, dark soils store huge amounts of carbon, helping stabilize the global climate. ✨
#grasslands⚡#soil⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Argentina’s Pampas are vast temperate grasslands that grow some of the world’s richest soils. These grasslands support massive cattle herds and store huge amounts of carbon underground. ✨
#grasslands⚡#pampas⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels