Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🚀🚀 Another massive profit made in Premium Group and this time it is#ZRX/USDT which crossed All the Profit Targets for an humongous gain of 33%
🗨Contact @futurechief to enter the Binance Futures/Bybit/Kucoin/OKX Premium Signal Group & Receive daily high quality signals by being in the Premium Group
#ZRX/USDT analysis :
#ZRX is in a downtrend, trading below the 200 EMA. The price is currently near the 200 EMA and is expected to reverse from this level, resuming bearish momentum and testing lower levels.
TF : 2h
Entry : $0.3200
Target : $0.2851
SL : $0.3500
#ZRX/USDT analysis :
#ZRX has successfully regained the 200 EMA and the previous support zone following a decline from its swing high. This recovery indicates a potential continuation of its momentum, with the price expected to test previous highs.
TF : 2H
Entry : $0.6490
Target : $0.9025
SL : $0.5250
#ZRX/USDT analysis :
#ZRX is currently consolidating within the resistance zone. The price is anticipated to reject from this level and test the previous support levels, where bullish momentum is expected to emerge.
TF : 15min
Entry : $0.3248
Target : $0.3161
SL : $0.3293
#ZRX/USDT analysis :
#ZRX is currently trading in the resistance zone below the 200 EMA. It's showing rejection at this level, and there's a strong anticipation that the price will continue its downward movement and test previous lows. It's advisable to wait for a confirmation break below the $0.2999 level before considering an entry.
TF : 2H
Entry : $0.2999
Target : $0.2502
SL : $0.3253
#ZRX/USDT analysis -
#ZRX is encountering rejection near a resistance zone, indicating a potential continuation of selling momentum. Prior to any trend reversal, it is anticipated that previous lows will be tested, leading to a potential continuation of the downward movement.
TF : 1D
Entry : $0.3763
Target : $0.2926
SL : $0.4086
🚀🚀 87% Profit on #ZRX/USDT for our Premium Members on Binance Futures/OKX/Bybit - All target completed
👁🗨Contact @primemod to enter the Premium Group and just trade on high quality SPOT & FUTURES Signals