Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#APE/USDT analysis :
#APE is currently demonstrating a bullish trend, characterized by higher highs and higher lows, with strong support along the trendline. The price has recently bounced back and successfully broken out of the trendline, suggesting a continuation of bullish momentum. It is anticipated that the price will test previous highs moving forward.
TF : 1D
Entry : $1.330
Target : $1.930
SL : $0.988
#APE/USDT analysis :
#APE is currently in an upward trend, consistently achieving new highs while trading above the 200-period exponential moving average (EMA). The price is currently consolidating above a support zone that has been tested multiple times. It is expected that the price will bounce off this level and continue its upward trajectory, with the potential to revisit previous highs.
TF : 30min
Entry : $1.890
Target : $2.160
SL : $1.760
#APE/USDT analysis :
#APE is currently in a downtrend, trading consistently below the 200 EMA. The price is currently within a resistance zone. It is anticipated to face rejection from this zone and continue its downward trajectory.
It is advisable to await the breakout of the $0.580 level for a short position, with the previous swing low likely to be tested.
TF : 30min
Entry : $0.580
Target : $0.537 and $0.509
SL : $0.607
📈Инсайдер «0x0b8a» превратил $174 000 в $2,45 млн (14x) всего за один день
Он открыл лонг по #APE прямо перед ростом цены и вышел почти на самом пике, зафиксировав $1,79 млн. Сразу после этого открыл шорт и заработал еще $488 000 – lookonchain.
🟪Чат▫️Новостной канал▫️Премиум сигналы
#APE
ApeCoin is completing a cup and handle formation on the daily chart🧐
Also, the price has breached above the descending resistancelevel and the MA 50
A move above the neckline could drive the price toward targets at $0.85, $1.00, $1.20, and $1.36🚀
#APE
ApeCoin is moving towards a key resistance level, showing potential for a significant move
A breakout from the descending channel could trigger a 100-120% bullish wave in the mid-term️