Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
$PEPE 🐸 has had quite the leap, falling 50% from its high, but the charts suggest a frog-leg kickback might be in sight! Can it reclaim $0.0000014 by Feb end? Only time will tell. #PEPE#Crypto#PricePrediction#Trading📈
📈BTC price at the time of this post: $48041
👉Continue reading
Bitcoin Price Prediction for 2025
James Butterfill, CoinShares head of research, forecasts Bitcoin to hit $80K-$150K in 2025. Trump's pre-election promises could influence the price towards the lower end, while better U.S. regulations might propel it higher. Long-term, Bitcoin's market cap may rise to 25% of gold's, potentially pushing prices to $250K, though this is not expected this year. Details: CoinShares Research
#Bitcoin#Crypto#VC#PricePrediction#MarketCap#Regulations#Gold
Bitcoin Price Predictions for 2025
CoinShares' James Butterfill forecasts Bitcoin to reach between $80K and $150K by 2025. Market corrections may arise due to unmet pro-crypto policies under Trump. A favorable regulatory environment could drive Bitcoin's value toward $250K long-term, increasing its share of the gold market from 10% to 25%. Meanwhile, Bhutan's government has mined Bitcoin for over five years, currently holding over $1.1 billion in Bitcoin as of December 2024. Read more
#Bitcoin#Crypto#Investment#MarketTrends#PricePrediction#Regulation#Bhutan#FinTech#Blockchain#VC
🚀 Zcash's Potential Surge: Traders Predict 60% Chance of Reaching $420
Zcash (ZEC) has experienced a significant rise, with traders on Myriad now predicting a 60% probability of the token reaching $420 this month. According to NS3.AI, Zcash saw an increase of over 62% in the past week, with its price recently hovering around $380. The odds on Myriad shifted dramatically from 80% against the move on Thursday to 60% in favor by Friday.
#Zcash#ZEC#Cryptocurrency#CryptoTrading#PricePrediction#Myriad#NS3AI#CryptoSurge#Blockchain#DigitalAssets
Ethereum ETF Sees Major Inflows
The Ethereum spot ETF recorded a net inflow of $139M last week, with Blackrock's Ethereum ETF, ETHA, gaining $135M. However, on January 27, the crypto market saw declines across sectors, with DeFAI down 28.73%. Other sectors like AI Agents saw a 16.91% drop. U.S. crypto czar David Sacks noted ongoing evaluations regarding Bitcoin and digital assets. Meanwhile, Rosseti, Russia's state power company, plans to introduce Bitcoin mining to leverage idle power resources. Runetoshi's new memecoin, Runes, faced volatility, dropping from $28M to $500k in market value. Arthur Hayes predicts Bitcoin could dip to $70,000 before a future rise to $250,000 this year. More on ETF inflows | Market drop details | David Sacks comments | Rosseti's Bitcoin mining | Runes token collapse | Hayes Bitcoin predictions
#Ethereum#ETF#Crypto#Bitcoin#Russia#Mining#Securities#Stablecoins#PricePrediction#DigitalAssets#Memecoin#MarketDrop#Runetoshi#DeFi#AI#QuantitativeEasing#USDC#WhaleAlert#MarketVolatility#FinancialCrisis#ArthurHayes