Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#SYS/USDT analysis :
The #SYS is currently in a downtrend, trading below the 200EMA. The price is testing resistance at the current level, and it's expected to decline further from there, potentially testing lower price levels.
TF : 2h
Entry : $0.0487
Target : $0.0410
SL : $0.0522
#SYS/USDT analysis :
#SYS is currently in a correction phase, experiencing a retracement toward the 200 EMA. This presents a potential long trade opportunity on lower time frame. Look for price to retrace and test the support zone for a long entry.
TF : 30min
Entry : $0.0676
Target : $0.0735
SL : $0.0644
#SYS/USDT analysis :
#SYS is currently consolidating sideways within the support zone and is expected to rebound from this level, potentially testing previous highs. It is advisable to wait for a pullback to establish a long position.
TF : 1D
Entry : $0.0964
Target : $0.1257
SL : $0.0822
BUYING $SYS HERE
Exchange: Binance / Binance Futures
Leverage: 3-5x
Breakout confirmed. Market conditions are perfect for an easy 100-200% move on #SYS
Targets: OPEN
SL: Below 0.0254
#SYS result
2 nd target achieved in just 11 hours ✅✅
One more huge quick profit 17% +🤑💰🤑
👉 Still thinking? The more you wait more you lose profit
☎️ Contact @MichaelStrategiesVip for membership and grab next breakout signal