Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🟧 .sats domain name is live on TokenPocket_TP!
👉http://tokenpocket.pro
🌟You can view the .sats domain name directly on the TokenPocket Transfer page after you enter the #Bitcoin wallet address!
Make #Bitcoin Great Again! #Ordinals#Bitcoin#SATs#TokenPocket $SATS
【Details】https://twitter.com/TokenPocket_TP/status/1734513835862798519
【Powered By】Crypto Box
🟧 Easily track the real-time #BRC20 Market on TokenPocket_TP!
✅Empowering you with real-time price updates and dynamic percentage changes! 📈
✅Providing you with a more stable and convenient wallet service!
👉https://www.tokenpocket.pro/
#Bitcoin#BRC20#SATS#ORDI
【Details】https://twitter.com/TokenPocket_TP/status/1739573022779170991
【Powered By】Crypto Box
Most people lose in crypto not because of the market, but because of emotions.
The solution is simple: accumulate BTC in small satoshi amounts regularly.
You can start with $100 today. This is not financial advice.
@saylor@APompliano@aantonop
#Bitcoin#BTC#Sats#HODL#CryptoEducation#MyMining
✨ Unlock simplicity in #BRC20 transfer!
🚀Now, easily transfer your #BRC20 assets in just ONE step!
🔄 Inscribe and transfer seamlessly for a more efficient and convenient experience.
👉https://tokenpocket.pro
Ready to experience seamless #BRC20 transactions?
Follow the tutorial:
👉https://help.tokenpocket.pro/en/wallet-faq-en/btc-wallet/brc20
#Sats#ordi#RATS#Inscriptions
【Details】https://twitter.com/TokenPocket_TP/status/1737707370523005390
【Powered By】Crypto Box
🟧 TokenPocket Now Fully supports BRC-20! #BRC20
✅#BRC20 tokens deposit, withdrawal, and token price display.
✅ Transfer your #BRC20 in one single transaction (Inscribe and Transfer in one step)
🆕We just released the iOS new version 🔺2.1.9🔺(TP Wallet) and Android new version 🔺1.9.5🔺. Upgrade your TP Wallet/TokenPocket and discover the #BRC20#Inscriptions world with us!
👉https://www.tokenpocket.pro/
#Sats#ordi#RATS#Inscriptions
【Details】https://twitter.com/TokenPocket_TP/status/1736949473048420555
【Powered By】Crypto Box
🟧Easily Track the hottest #BRC20 tokens on TokenPocket_TP!
Still not too late to know this secret! 😍
✅Click the "+" button on the #Bitcoin Asset page, and you can view the trending token list directly! Figure out what are most TokenPocket users interested in and get a chance to find a #GEM💎 with your #TokenPocket Wallet!
👉https://www.tokenpocket.pro/
#ORDI#SATs#BIIS#RATS
【Details】https://twitter.com/TokenPocket_TP/status/1737405949722366261
【Powered By】Crypto Box