Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#DEGO/USDT analysis :
#DEGO is currently in a downtrend, trading below its 200 EMA and encountering resistance. This suggests a potential continuation of the downtrend, for short entry opportunity wait for pullback.
TF : 4h
Entry : $1.537
Target : $1.270
SL : $1.712
#DEGO/USDT analysis :
#DEGO is currently in an uptrend, consistently reaching new highs while trading above the support zone. Following a strong impulsive move, the price has undergone a correction phase. It is now anticipated to bounce from this level and continue rising, aiming to test previous highs. For a long entry, wait for a breakout above the $1.996 level.
TF : 4H
Entry : $1.996
Target : $2.490
SL : $1.757
#DEGO/USDT analysis :
#DEGO is currently in an uptrend, forming higher highs and higher lows above the 200 EMA. The price is presently consolidating above the support zone and is expected to bounce from there to sustain its bullish momentum and test the previous swing high.
TF : 1h
Entry : $1.640
Target : $1.696
SL : $1.608
🚀🚀100% Huge Profit on #DEGO/USDT as it has hit all the profit target - The trade has been closed
👁🗨Contact @primemod to enter the premium group & make daily gains