Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#TFUEL/USDT analysis :
#TFUEL is currently forming a symmetrical triangle pattern on the monthly timeframe. The price is showing strong volume, indicating that a breakout from this pattern is likely to occur soon that can continue its upward momentum and test higher levels. A potential gain of around +620% is anticipated from the current level.
TF : 1M
Entry : $0.09330
Target : $0.67520
SL : $0.06149
#TFUEL/USDT analysis :
#TFUEL has bounce back from the support zone and break above the trendline. Price is expected to continue its bullish momentum and test previous highs.
TF : 4h
Entry : $0.06237
Target : $0.06954
SL : $0.05766
#TFUEL/USDT analysis :
#TFUEL is currently consolidating sideways near the resistance zone. The price is unable to break the zone upside and facing resistance. It's expected that the price will continue its bearish momentum from the current zone to test the previous swing low.
TF : 4H
Entry : $0.05740
Target : $0.04363
SL : $0.06297
#TFUEL/USDT analysis -
#TFUEL is in a downtrend on the HTF. The price is expected to continue its momentum, and previous lows will be tested. Before entering a short position, wait for a retracement for entry.
TF : 4H
Entry : $0.06791
Target : $0.06011
SL : $0.07132
#Tfuel Falling Wedge Breakout Has Confirmed Overall Consolidating In Symmetrical Triangle Expecting Move Towards In Descending Trendline In Coming Days And Once Trendline Got Cleared Can Easily Test 0.30$ In Midterm