Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#HOT/USDT analysis :
#HOT has broken and retested the support levels, which are now acting as resistance for the price. The price is currently in a downtrend on the higher timeframe and is expected to continue its momentum from the current level.
TF : 1H
Entry : $0.00135
Target : $0.00123
SL : $0.00142
#HOT/USDT analysis -
#HOT is currently consolidating sideways above a support line. The price has tapped into liquidity from previous lows below the support line. It appears poised to move upwards, with the previous high as the target level.
TF : 5min
Entry : $0.00145
Target : $0.00150
SL : $0.00143
#HOT/USDT analysis -
#HOT is currently on a downtrend, trading below the 200 EMA. At the moment, it's experiencing a pullback and has retraced to previous support levels near the 200 EMA. The price is encountering resistance near the 200 EMA and appears poised to start moving downwards. It's likely that the price will test previous lows in the near future.
TF : 1h
Entry : $0.00184
Target : $0.00162
SL : $0.00201
4834 new target 5000 🔥
🔥Claim/198 activationsFiredrop 0.25 HOT
How to claim:
╔•1.Join our village.
╠•
╚•2.Subscribe claim 0.25 HOT
🎁Gifts, NFTs, stars, premium Telegram, crypto airdrops, and tokens like 🔥HOT and more! Premium 👥VIP status! Join and win every day!
#hot
#HOT rejected from the ceiling of supply zone on 3D Time frame,it can bounce again from the Green zone, everything is bullish now
📈
❄️@signals_bitcoin_crypto❄️
❄️@Shadow_support0o❄️
🪙1853 new target 2000 #HOT🔥
How to claim:
1) Join our village.
2) Follow @ChatCryptoTON
🔥Claim 170/288 activationsFiredrop0.15 HOT
🔥Claim/88 activationsFiredrop0.25 HOT