Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#PEOPLE/USDT analysis :
#PEOPLE is in a downtrend, forming lower lows (LLs) and lower highs (LHs) below the 200 EMA. The price is currently facing resistance and is anticipated to decline from there, testing lower levels.
TF : 2H
Entry : $0.01564
Target : $0.01359
SL : $0.01710
#PEOPLE/USDT analysis :
#PEOPLE is currently retracing towards the 200 EMA, before continuation of bearish momentum. The current support level is favorable for long entry, as bullish momentum is anticipated on the lower time frames.
TF : 1h
Entry : $0.01970
Target : $0.02496
SL : $0.01726
#PEOPLE/USDT analysis :
Price is in a downtrend forming lower lows (LLs) and lower highs (LHs) below the 200 EMA. The price is expected to continue its bearish momentum and exhibit further decline in price from the current resistance zone.
TF : 1H
Entry : $0.0582
Target : $0.0497
SL : $0.0629
✅✅ 47% Profit on #PEOPLE/USDT for our Premium Members on On Binance Futures, Bitget Futures, ByBit USDT, KuCoin Futures, OKX Futures
👆🏻All Profit Targets Successfully Completed
👁🗨Contact @primemod to enter the most powerful premium group & make daily gains