Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#FXS/USDT analysis :
#FXS has broken below the 200 EMA and the support zone. It is advisable to wait for a price retest of this zone for a potential short entry, as the price is anticipated to decline further, targeting lower levels.
TF : 4h
Entry : $3.455
Target : $2.400
SL : $3.945
#FXS/USDT analysis :
#FXS has successfully broken out and retested the swing high resistance following the breakout of the trendline in an established uptrend. The price is expected to sustain its bullish momentum and aim for previous highs.
TF : 30min
Entry : $4.762
Target : $5.080
SL : $4.526
#FXS/USDT analysis :
#FXS is currently in a downtrend and is expected to maintain its bearish momentum. For a short entry, wait for the price to break the current support zone, entering on a break below the $1.814 level. The previous lows will serve as target levels.
TF : 15min
Entry : $1.814
Target : $1.797
SL : $1.826
#FXS/USDT analysis :
#FXS is in a downtrend, forming lower lows (LLs) and lower highs (LHs) structure. The price is currently trading in the resistance zone near the 200 EMS. It is expected to be rejected from that area and continue its bearish momentum.
TF : 30min
Entry : $1.734
Target : $1.651
SL : $1.792