Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
It might look a little confusing at first, but pay attention.
On this chart we have DXY, GOLD and BTC.
DXY, which is a representative chart of the USD, has an inverse relationship with GOLD and BTC.
This is because when the dollar is strong, big money moves into high interest bonds that are safe.
When the dollar weakens, big money moves into safe havens and riskier assets.
What we can firstly see on the chart is that every time DXY drops, GOLD almost instantly moves higher.
Secondly, we can see that BTC also moves higher, but it lags behind GOLD.
But that’s not the most interesting thing…
The most interesting thing here is that every single time DXY has entered a down trend, BTC has began its move between 133 days and 140 days later.
This time, that gives us an end of May date as to when BTC will begin its next true move higher.
It’s just facts, right there for you to see.
#CryptoSignal#Binance#PumpAlert#FuturesTrade
30 day PNL screenshot14 New tarde profit ✈️✈️If you're want this
Type profit in 7 days ..
✅ Don’t miss the next big move — join our VIP Premium Channel now!
📩 Contact: @Future3366
🚀 Real-time signals | Pump alerts | Future trades
#CryptoSignals#VIPAccess#BinanceFutures#PumpAlert#CryptoProfits