Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🚀BubbleMaps (BMT) Airdrop is LIVE on Binance! 🎉
Earn FREE $BMT with Retroactive BNB SimpleEarn Subscriptions! If you held BNB in Simple Earn (Flexible/Locked) or On-Chain Yields (March 2 - 6, 2025) you may qualify! 🎁
🔥 Why BubbleMaps?
✔️ Track token movements & uncover hidden links 🔍
✔️ Integrated with CoinGecko, DexScreener & more 💡
✔️ BubbleMaps V2 unlocks new features with $BMT🚀
📈$BMT Trading Pairs on Binance:
🔹 BMT/USDT | BMT/USDC | BMT/BNB | BMT/FDUSD | BMT/TRY
⚙️ How to Participate?
📥Check Your Eligibility & Claim Here:
👉Register & Claim Now
📢Stay Updated & Join Our Community:
🔗BubbleMaps Official Telegram
®Note - Please do your own research (DYOR) before joining to any airdrops project, also airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens
#BubbleMaps#BMT#Binance#Airdrop#Crypto
Simplifying Processes: A Billion-Dollar Idea
A new startup aims to simplify image and video management, outperforming Dropbox. This innovation has attracted nearly $70 million in investments, capitalizing on a $2 trillion creative economy. Additionally, Bubblemaps has launched its BMT token on Solana, offering on-chain analytics and community governance, hinting at a potential airdrop. Deribit, a major crypto derivatives exchange, is exploring acquisition offers, valued between $4-5 billion, with Kraken showing interest.
#Startup#Dropbox#Investment#CreativeEconomy#Bubblemaps#BMT#Token#Solana#Crypto#ETFs#Derivatives#Kraken#Airdrop#VC#AI#Blockchain#Innovation#Finance
🚀 Crypto Analyst Manya Releases Research Tool Rankings
Crypto analyst manya has released a ranking of personal research tools. According to ChainCatcher, the rankings categorize tools into different levels based on their effectiveness. The S-tier includes Dune and frontrun.pro, while the A-tier features Coinglass, RootData, Drop, MetaSleuth, and DefiLlama. B-tier tools comprise Arkham, Bubblemaps, Dexscreener, Surf, Nansen, and CoinMarketCap. C-tier tools include Cryptorank and others.
#CryptoAnalyst#ResearchTools#CryptoRanking#Dune#frontrunpro#Coinglass#RootData#Drop#MetaSleuth#DefiLlama#Arkham#Bubblemaps#Dexscreener#Surf#Nansen#CoinMarketCap#Cryptorank