Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
BitFuFu Secures Major Mining Deal
BitFuFu signs two-year agreement with Bitmain to purchase up to 80,000 S-series bitcoin mining machines for self-operated mining. More details on the deal here: link
#Bitcoin#BitFuFu#Bitmain#Mining#Miners#Crypto
🖤Blockchain Life 2025 Sum up
Dubai, Oct 23, 2024 — The 13th edition of the Blockchain Life Forum, the premier gathering for cryptocurrency leaders worldwide, recently concluded with an astounding attendance of over 12,119 participants.
😎 The forum showcased over 200 esteemed speakers, featuring industry pioneers and executives from top companies, including #OKX, #CoinMarketCap, #Bitmain, #Bybit, #Binance, #AnimocaBrands, #Circle, #BingX, #ICP, #Kraken, #TON and many more.
📱 The exhibition of crypto companies featured 125 amazingly beautiful booths. Major players such as #OKX, #Bitmain, #BingX, #KuCoin, #Bitget, #ListingHelp, and #Uminers.
🎧 As a spectacular finale to the forum, participants enjoyed the Legendary #AfterParty at one of the world’s premier clubs, SKY2.0. This informal networking event provided a platform for top industry figures to connect, complemented by a dazzling live performance from internationally celebrated artist French Montana, who thrilled over 1,200 attendees with his chart-topping hits.
See you at Blockchain Life 2025!
The early bird tickets and sponsorship application for Blockchain Life 2025 are already open – follow the link:
https://blockchain-life.com