Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Fishy Business is OUT NOW! 🐟💰
No more waiting—our top catch of the year has surfaced! Fishy Business delivers high volatility undersea action with 25 paylines, Hold'n'Win thrills, and a shot at x5000 max wins. The Bassline Bonanza Free Spins make this one dive you won’t want to miss, as reels 2, 3 and 4 convert into one huge symbol for some truly huge wins! 🌊⚡
Ready to take the plunge? 🤿
🎰 SPIN IT: https://bit.ly/fishy-business-demo
#FishyBusiness#OutNow#HoldnWin#TrueSlots#TrueGames#TrueLab
🔞 | Play Responsibly
The Wait is Over — Hot Devil Slot is Here! 😈
Kick off our HOT Series with a spin that’s hotter than your ex and easily twice as fun. Ready to play with fire or just here to warm up? With classic gameplay turned up to inferno levels, every spin is destined to thrill.
Let the games begin! 🔥
🍒 IGNITE THE FUN: https://play.truelab.games/game/hot-devil-slot-v1/static/index.html
#HotDevilSlot#OUTNOW#igamingnews#TrueLab#TrueSlots#TrueGames
🔞 | Play Responsibly
BOOM! The Fruit Circus Party is in town tonight! 💥
The wait is over, so It's finally time to unleash those unlimited multiplicative multipliers and kick off the mayhem!
Use the Buy Bonus to plunge straight into the bonus round, where multipliers only head in one direction - UPWARDS. Because who needs limits, right?
Fruit Circus Party is OUT NOW! 🚀
➡️ SPIN IT: https://bit.ly/demo-fcp
#FruitCircusParty#OUTNOW#MultiplicativeMultipliers#BuyBonus#TrueLab#TrueGames#TrueSlots
🔥💸 Feeling Lucky? More like feeling HOT! 💸🔥
HOT MONEY SLOT, the second game in TrueLab’s Hot Series, is OUT NOW. We’ve taken those good old fire and fruit line 3x3 mechanics and turned up the heat with top-notch graphics and sound.
The Hot Series games are the perfect complement to any game portfolio. Do you prefer quick action with a classic vibe but can't get yourself to revisit the oldies? This one's for you. Let's go. 🎰
➡️ SPIN IT: https://bit.ly/Hot-Money-Demo
#HotMoneySlot#OutNow#HotSeries#iGamingNews#TrueLab#TrueGames#TrueSlots
🔞 | Play Responsibly
100 HOT SLOT is OUT NOW!
As the grand finale of our three-way TrueLab Hot Series, this classic slot features 100 lines for maximum enjoyment and fiery fun. 🍒🍉🍋🔥
Don’t miss out on this blazing conclusion to our Hot Series!
SPIN IT! ➡️https://bit.ly/100HS-Demo
#100HotSlot#HotSeries#OutNow#FruitAndFire#ClassicSlots#TrueLab#TrueGames#TrueSlots
This isn't just a book
It’s the story of the rhythm that moved the world and changed the face of music forever.
Don't just listen to the music understand the journey that made it happen.
https://www.amazon.co.uk/dp/B0GCMSHW1F
#BenEccles#OutNow#AmazonBooks#LaunchDay#MusicHistory#NewBookAlert#AfrobeatsWorld#ReadTheRhythm#OfficialRelease