Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#SXP/USDT analysis :
#SXP has broken out of the trendline, and the price has also rebounded from the support zone following a period of sideways consolidation. It is anticipated that the price will continue to rise from the current level and test previous swing highs.
TF : 1D
Entry : $0.3240
Target : $0.5629
SL : $0.2055
#SXP/USDT analysis :
#SXP has bounced back from the 200 EMA after a retracement and a breakout of the trendline. It is now expected to move towards the previous swing high level.
TF : 2H
Entry : $0.2592
Target : $0.2894
SL : $0.2495
#SXP/USDT analysis :
#SXP is presently in an uptrend, forming higher highs (HHs) and higher lows (HLs). It is expected to experience a pullback near its support zone and is likely to bounce back from there to test higher levels.
TF : 1h
Entry : $0.2416
Target : $0.2538
SL : $0.2339
✅✅ 150% Profit on #SXP/USDT for our Premium Members on Binance Futures/Bybit Futures/OKX Futures& KuCoin Futures
👁🗨Contact @primemod to enter the premium group & make daily profit
#SXP bounced from the support zone on Weekly time frame,now price is trying to break up the falling wedge pattern, breakout incoming..
📈
❄️@signal_bitcoins❄️
❄️@Shadow_support0o❄️