Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#CELR/USDT analysis :
#CELR is currently forming a triangle pattern. A breakout from this pattern is anticipated, with the price expected to test previous highs. A long entry is recommended upon a breakout above the $0.02130 level.
TF : 1D
Entry : $0.02130
Target : $0.03180
SL : $0.01695
#CELR/USDT analysis :
#CELR is currently in a downtrend, trading below the 200 EMA. The price is currently facing resistance in this zone. It is expected to reverse from this point and continue its bearish trend to test previous lows. Wait for a breakout below the $0.01114 level to consider going short.
TF : 4H
Entry : $0.01114
Target : $0.01014
SL : $0.01169
#CELR/USDT analysis :
#CELR is in a downtrend, trading below the 200 EMA. The price is forming LLs and LHs structure. Before continuing its bearish momentum, the price is expected to experience a pullback and test the resistance zone. Wait for the pullback for a short entry.
TF : 1H
Entry : $0.01142
Target : $0.01043
SL : $0.01177
#CELR/USDT analysis -
#CELR is in a downtrend, trading below the 200 EMA. The price is currently approaching a resistance zone. It is expected to be rejected from there and continue the bearish momentum towards the previous lows.
TF : 4h
Entry : $0.0157
Target : $0.0129
SL : $0.0164
#CELR/USDT BUY SETUP
CELR has broken out of the descending triangle and is currently testing it. A successful test will confirm a bullish move. Get ready for takeoff. 🚀