Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🌍 Tropical peat swamp forests store massive amounts of carbon in deep, soggy soils. Some areas in Southeast Asia hold peat deposits over 10 meters thick, locking away centuries of trapped carbon. ✨
#rainforest⚡#carbon⚡#wetlands⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some freshwater wetlands and deltas trap so much carbon in their soil that, hectare for hectare, they store more than most forests—making them powerful natural climate regulators. ✨
#wetlands⚡#delta⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Arctic tundra’s permafrost acts like a giant freezer, locking away twice as much carbon as all the world’s forests combined, making it a crucial regulator for Earth’s climate. ✨
#permafrost⚡#tundra⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The global carbon cycle constantly moves carbon between the air, land, water, and living things. This cycle helps regulate Earth’s climate by storing and releasing carbon dioxide. ✨
#carbon⚡#climate⚡#cycles⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Canada holds more than 30% of the world’s forests, making it the top country for natural forest area. These forests store massive amounts of carbon and water—critical global natural resources. ✨
#resources⚡#forests⚡#carbon⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
Grand Power кобура скрытого ношения на быстросъёмных крепежах с мягким слоем Alcantara внутри.
Двойной подсумок
Кобура скрытого ношения с Alcantara, с дополнительным магазином.
➡️#grandpower
➡️#моноблок
➡️#carbon
НЕ ПРОДАЖА ОРУЖИЯ! ⚠️
Демонстрируется только для наглядности функционала.
По вопросам заказа связывайтесь с нами📱
ПОДПИСЫВАЙТЕСЬ ЧТО БЫ НЕ ТЕРЯТЬСЯ:
📱MAX
📱VK
@DP_KH
🌍 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