Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#ENS is rebounding from the support trendline of the descending channel, with the Ichimoku Cloud acting as a resistance barrier.
A decisive breakout above both the channel and the cloud would confirm bullish momentum.
#ENS/USDT analysis :
#ENS is currently in an uptrend, consistently reaching new highs while trading above the 200 EMA. The price is now retracing towards the 200 EMA and a significant support level. It is expected that the price will test this zone and rebound, which should support the continuation of bullish momentum and will lead to a retest of previous highs.
TF : 1D
Entry : $30.35
Target : $47
SL : $23.38
#ENS/USDT analysis :
#ENS is currently in an uptrend, trading above the 200 EMA. The price has recently bounced back from the 200 EMA, suggesting a continuation of its bullish momentum and potential testing of higher levels. For a long entry, it is advisable to wait for a retracement to optimize the entry point.
TF : 30min
Entry : $43
Target : $48
SL : $38