Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#JUV/USDT analysis :
#JUV is currently in a bearish trend, forming lower lows (LLs) and lower highs (LHs) below the 200 EMA. The price is expected to maintain its bearish trajectory and test lower levels from the current position.
TF : 1h
Entry : $1.033
Target : $0.914
SL : $1.105
#JUV/USDT analysis :
#JUV is forming a structure of higher highs (HHs) and higher lows (HLs). The price is expected to break out above the 200 EMA resistance and continue to rise. It is advisable to wait for the price to retest the support zone for a long entry opportunity.
TF : 2h
Entry : $1.640
Target : $1.780
SL : $1.550
#JUV/USDT analysis :
#JUV is presently being rejected from the resistance zone. The price is expected to retrace towards the 200 EMA and test it. This could potentially create a short trade opportunity on the lower time frame (LTF).
TF : 1H
Entry : $1.636
Target : $1.592
SL : $1.663
#JUV result
2 nd target achieved in just 1 days ✅✅✌
One more huge quick profit 21.2%🤑💰🤑
👉 Still thinking? The more you wait more you lose profit
☎️ Contact @MichaelStrategiesVip for membership and grab next breakout signal
#JUV result
1 st target achieved in just 21 house ✅✌
One more huge quick profit 10.3%🤑💰🤑
👉 Still thinking? The more you wait more you lose profit
☎️ Contact @MichaelStrategiesVip for membership and grab next breakout signal