Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
MicroStrategy(@Strategy) bought another 1,895 $BTC($180.34M) at an average price of $95,167 last week.
#Strategy currently holds 555,450 $BTC($52.35B), with an average buying price of $68,550 and an unrealized profit of $14.28B.
#CryptoSignals#FuturesTrading#VIPGroup#BTC#Altcoins#CryptoProfit
🚀 Crypto Trader 'Maji' Increases Long Positions Amid Market Fluctuations
On April 11, 'Maji' continued to strategically increase long positions, according to BlockBeats. The total value of these positions has risen to $42.17 million, up from approximately $34 million the previous evening. These positions are reported to have a high safety margin, with liquidation prices significantly lower than current market values.
As of the latest update, 'Maji' holds detailed positions including a 25x leverage on Ethereum with 12,131.7179 ETH at a liquidation price of $2,090.95, a 40x leverage on Bitcoin with 180 BTC at a liquidation price of $62,529.3, and a 10x leverage on HYPE with 43,750 units.
Additionally, 'Maji' has achieved a total contract profit of $1.85 million over the past week, and has turned a monthly loss into a profit of $190,000.
#CryptoTrading#Maji#LongPositions#MarketFluctuations#Ethereum#Bitcoin#LeverageTrading#CryptoProfit#HYPE#ContractProfit#BTC#ETH
🔥@CryptoDailyPrice – Your shortcut to daily crypto power! 💰
Get live price updates, learn pro trading tricks, and discover zero-investment earning hacks that actually work. 🚀
Stay tuned — every post drops something crucial, profitable, and mind-opening for crypto lovers like you! ⚡
#CryptoDailyPrice#CryptoUpdates#CryptoEarnings#CryptoTrading#CryptoTips#LearnToTrade#ZeroInvestment#CryptoForBeginners#DailyCryptoNews#PassiveIncome#CryptoSignals#CryptoMarket#CryptoProfit#StayTuned#EarnWithCrypto