Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#GRT/USDT analysis :
#GRT has broken out of its trendline with strong momentum following a bounce back from the support zone. The price is expected to maintain its bullish momentum and test previous highs. The current level presents a favorable entry opportunity.
TF : 1W
Entry : $0.2023
Target : $0.3446 and $0.4902
SL : $0.1450
#GRT/USDT analysis :
#GRT is currently in a downtrend, making lower lows (LLs) and lower highs (LHs), and is trading below the 200 EMA. The price is facing rejection from both the 200 EMA and the resistance zone. It is expected to decline from this point and potentially test the previous swing low.
TF : 1D
Entry : $0.1682
Target : $0.1294
SL : $0.1940
💰#GRT has a falling wedge pattern on 8H Time frame, we expec it will pump alot in the case of breakout, waiting now..⌛️
❄️@signals_bitcoin_crypto❄️
❄️@Shadow_support0o❄️
💰#GRT bounced back from the Support zone on 12H Time frame, we are waiting for breakup and pullback to the broken trendline 💫
❄️@signals_bitcoin_crypto❄️
❄️@Shadow_support0o❄️