Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
SEC Accepts Grayscale's DOGE ETF Application
The U.S. SEC has accepted Grayscale and NYSE's 19b-4 application for a DOGE ETF. This marks a significant step in the integration of Dogecoin into mainstream finance. Read more.
In other news, GameStop is considering an investment in Bitcoin and other cryptocurrencies while evaluating alignment with its business strategy. More details can be found here.
Coinbase reports over a 130% revenue surge, reaching $2.3 billion for Q4, exceeding expectations. Full report reveals strong market performance.
Additionally, Frodobots successfully raised $6M for a Solana-based robotics network. Learn more.
#DOGE#ETF#GameStop#Bitcoin#Crypto#Coinbase#Revenue#Solana#DeFi#AI # VC
Bitcoin and Ethereum ETF Trends
BTC ETF saw $157M outflow; ETH ETF gained $13M inflow. In 24 hours, 94K traders liquidated, totaling $169M, with the largest being $1.3M on Bybit for BTC/USDT. Notably, 4,135 #BTC ($399.8M) moved from #Coincheck to an unknown wallet. Gamestop plans to invest $4.6B in Bitcoin, raising its stock prices. Meanwhile, 1723HK shares surged 631% this year, naming new directors with Bitcoin ecosystem expertise.
#BTC#ETH#ETF#Crypto#Gamestop#Coincheck#WhaleAlert#HongKong#Investment#StockMarket#Trading#Liquidation#MarketTrends#Blockchain#Finance#Innovation#Directors#Performance#News#AI#VC
ETH Deposits Surge on Bybit
Aave's ETH supply surpassed 2M for the first time. Mirana Ventures deposited $600M worth of ETH into Bybit, becoming the largest depositor since the hack. The firm sold $500M in Bitcoin and $100M in USDT to fund this. In addition, $130M in USDT transferred to Tether Treasury. Significant BTC movements reported as well. Full details in the links: Arkham, The Block, Whale Alert USDT Transfer.
#ETH#Aave#Bybit#Crypto#USDT#BTC#MiranaVentures#DeFi#Arkham#Treasury#GameStop#SEC#Uniswap#AlgorithmicTrading#Blockchain#Investments#Bitcoin#WhaleAlert#Fintech#VC
Roaring Kitty Hints at Comeback
🐦 Roaring Kitty, a key figure in the GameStop stock surge, teases a return. His recent tweet features a video, sparking nostalgia and speculation about upcoming moves. Kitty symbolizes retail investor resistance against Wall Street, igniting the meme stock revolution in 2021.
🔗Roaring Kitty's tweet
🔗 Whale Alert: $102M in #BTC transferred Details here
🔗 Bithumb launches new ARDR & QKC trading Read more
#GameStop#RoaringKitty#memeStocks#BTC#Crypto#VC#RetailInvestors#WhaleAlert#SouthKorea#Trading#Bithumb#ARDR#QKC#Investing#MarketNews#Finance#Nostalgia#Tease#Speculation