Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🚨 Only 1 day left until the Top Club Referral event ends! ⏳
Don't miss your chance to invite more members to your club and win amazing rewards from SingSing.
Act fast and make your club the best 👉link🌟
🥇Top 1: 10,000 RUBY shared among all Club Members + 0.01 ETH for Club Owner
🥈Top 2-4: 5,000 RUBY shared among all Club Members + 0.007 ETH for Club Owner
🥉Top 5-7: 3,000 RUBY shared among all Club Members + 0.003 ETH or Club Owner
🏅Top 8-10: 2,000 RUBY shared among all Club Members
Total prize pool: 20,000 RUBY and 0.02 ETH! 💎✨
Note: Top clubs will be determined by the number of members joining through each club's referral link.
Read more and open Treasure at: X Post
#SingSing#TopClubReferral#LastChance
🚀 Great Start of SLEX Launchpad!🎉
⚡️The first day of SLEX Launchpad sales was a huge success with over 37,78% of allocations sold out! Whitelist participants, you have a last chance to be part of this exclusive event, but hurry up as allocation actively decreases with high users demand📈
🗓️The sale ends tomorrow, February 17th. Don't miss the last chance to take exclusive advantages of SLEX Launchpad.
#SLEXLaunchpad#LastChance#CryptoSale
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
📣 Final Call for SLEX Rewards! 🌟
🎁Dear, SLEXians, our rewards form is closing soon! Don’t miss your last chance to claim tokens SLEX. Fill out the Zealy contest form by the 24th of November 2023🎉
🏃♂️💨 Hurry, time is ticking, and this is your final reminder. Complete the process to ensure you don’t miss out!
👉bit.ly/3s3Ey46👈
#SLEXRewards#LastChance#CryptoCommunity#SLEXPrizes
Email | Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🚨 RUBY Mining Feature Closing at 13:00 UTC on Sep 23! 🚨
Today’s your last chance to mine and claim RUBY! ⏳⛏💎
RUBY is still essential for several game features and boosting your in-game earnings, so don’t miss out! 🎮💰
Get those final rewards before the feature shuts down!
#SingSing#RUBYMining#LastChance#GameBoost#SingSingTycoon
🎤Announcement | Chat | X (Twitter) | Website | Game