Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#Sentiment notes that the activity of #BTC discussion on social media has risen to a 4-month high, there is a serious panic among the crowd. Such depressive indicators in the moods usually preceded the rebounds.
⚡️ Sentiment notes a decrease in the number of wallets with a non-zero balance 🪙#BTC, which may mean that some participants will enter the cache before the US elections. The experts of #Sentiment consider this development of the situation to be #bullish for #BTC after the elections are held...
#Sentiment notes a sharp rise in bullish sentiment in #Solana
there are rumors that #Apple (#AAPL) is starting to use the Solana — Sentiment blockchain
🤣Ethereum Fear & Greed Index has dropped to 13, signaling Extreme Fear across the market.
市場情緒跌入 極度恐懼區間,代表短期資金風險偏好明顯下降,投資人情緒趨於保守。
#Crypto#以太坊#币圈#区块链
⚡️ 歷史上極度恐懼區域,往往出現在市場接近階段性底部時,但短線波動仍可能持續。
#Ethereum#Markets#Sentiment
———
👇⭐️👇
🤣留言分享觀點
🥲👇