Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🚀 Analyst Discusses Stop-Loss Adjustment Strategy
An analyst, @ai_9684xtpa, posted on X about the rationale behind adjusting a stop-loss point to $73,500. The adjustment was made to prevent precise liquidation, and the analyst noted that the price nearly reached this adjusted level.
#StopLoss#TradingStrategy#MarketAnalysis#RiskManagement#PriceAdjustment#Investing
🚀 Bitcoin's Current Volatility May Present a Generational Buying Opportunity
Cryptocurrency analyst Ali Martinez recently shared an analysis on the X platform, suggesting that instead of debating whether Bitcoin has hit its bottom, attention should be focused on whether the current volatility presents a 'generational buying opportunity.' According to Odaily, Martinez identifies key 'value zones' for the current cycle based on long-term trend lines, on-chain liquidity, and cost distribution indicators.
The UTXO Realized Price Distribution (URPD) indicates a significant concentration of holdings between $63,111 and $70,685, forming the primary support band. If Bitcoin falls below $63,111, the market may enter a liquidity vacuum.
From a long-term perspective, Bitcoin is nearing a critical ascending trend line from the past decade, approximately between $56,000 and $60,000. Historically, this position has often marked the accumulation phase before significant price increases.
In more extreme scenarios, the CVDD indicator suggests a structural bottom around $47,960, while the MVRV 0.8 range at approximately $43,647 indicates a market in an 'extreme pain' phase, typically associated with exhaustion of selling pressure. In the event of a black swan event, prices could briefly dip to an extreme range of around $36,657.
Based on these zones, Martinez employs a dollar-cost averaging (DCA) strategy, gradually increasing positions across different support bands to reduce overall holding costs. He believes the market is currently in a phase of low sentiment, but potential opportunities are gradually emerging.
#Bitcoin#Cryptocurrency#CryptoTrading#MarketAnalysis#Volatility#InvestmentOpportunity#DCA#OnChainAnalysis#CryptoMarket#TradingStrategy#BTC
Melania Meme Token Debuts on Major Exchanges
Centralized exchanges like MEXC, BingX, Gate, and Bitget list Melania Meme (MELANIA) token. The token's economic model: 35% team share (30-day lock), 20% treasury, 20% community, 15% public offering, 10% liquidity. Major transaction: an address bought 3.8M MELANIA for 800k USDC, now with a profit of $38.6M.
Read more: Wu Blockchain News
#Crypto#MemeToken#MELANIA#TrumpProject#Dogecoin#Bitcoin#Profit#Exchanges#Trading#Finance#USDC#MarketAnalysis#Tokenomics#Investment#TradingStrategy#Speculation#ProfitableAddresses#MarketTrends#Blockchain#Web3#VC
Binary trading isn't gambling if you have the right tools.
📈 Watch how Pro Thunder V12 identifies the signal on MT5 before I even open the broker. No repainting, no delay, just pure accuracy.
#binaryoptions#pocketoption#quotex#tradingstrategy#mt5#forexsignals#otctrading#daytrading#prothunderv12#fintok#wealthbuilding#tradingtips#makemoneyonline#investing2026
Traders Face Major Losses with LIBRA Coin
Nansen research reveals that 86% of LIBRA coin traders lost money, totaling $251 million in investor losses. Meanwhile, insiders profited over $100 million from the token issuance. For more details, visit CoinDesk.
#LIBRA#Argentina#Crypto#Investors#Losses#Trading#Nansen#Market#Finance#Tokens#Wealth#Volatility#DeFi#Research#Blockchain#Memecoin#VC#Funds#Loss#Insiders#TradingStrategy