Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🚀🚀Raining Profits in the Premium Group
🎯🎯#BAT/USDT has covered all the targets to give an amazing profit of 21% for all Premium Members
👁🗨Contact @futurechief to enter the premium group & make daily gains on Futures as well as Spot Market
#BAT/USDT analysis :
#BAT is in an uptrend, consistently making new highs while trading above the 200 EMA. Currently, the price is above the support zone and is expected to bounce back from this level, resuming its bullish momentum to test previous highs.
TF : 1D
Entry : $0.2250
Target : $0.2943
SL : $0.2027
#BAT/USDT analysis :
#BAT is presently consolidating within a channel. The overall trend on the larger timeframes indicates a bearish outlook, suggesting a potential breakout from the channel to continue moving downwards towards lower price levels. It is advisable to wait for a breakout of the channel and a decline below the $0.1564 level for a short position entry.
TF : 2H
Entry : $0.1564
Target : $0.1313
SL : $0.1640
#BAT/USDT analysis -
#BAT is currently in downtrend, trading below the 200 EMA. The price is in a pullback phase and is projected to test the resistance zone close to the 200 EMA before potentially dropping further to revisit the previous lows. It is recommended to await the price to test the zone before considering a short entry.
TF : 4h
Entry : $0.1970
Target : $0.1728
SL : $0.2067