Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
✨ WEEKLY LEADERBOARD UPDATE: WEEK 3 FEBRUARY CHAMPIONS! 🔼
The battle was intense, but these Gumart residents dominated the game! 🚀 Let’s celebrate our top performers who secured their spots at the top.
🏆 Top Achievers – Week 3 February:
🥇1st Place:@rich***00 - 50 USDT
🥈2nd Place:@Bury***ke - 20 USDT
🥉 3rd Place: @aoi_***ng - 20 USDT
🎮 Top 10 Most Engaged in Gumart Chat:
Each winner receives 10 USDT for keeping the conversation alive! (English messages only)
🏅 Winners, check your bot notifications and claim your rewards! The next leaderboard race is ON – will you be the next champion? ⚔️💰
#Minigame
Join the KardiaChain ♥️ Mass Adoption Mini Games for a chance to win a part of 200$!
UTC 12:00 17th Oct - 12:00 19th Oct
🎮Game Mechanics below 👇🏻
Mini Game 🎮 1:
1. Go to 🌐https://forms.gle/de2UYK7onyduqmVn8
2. Submit the correct answer the fastest to win 25$
3. Next 5 submissions with the correct answers also gets 10$ Each
Mini Game 🎮 2:
1. Go to KardiaChain's♥️ TelegramCommunity
2. Submit you proposal idea on the thread here about the future of Web 3.0 and what KardiaChain's next steps should be on the path of achieving mass adoption.
3. Receive the most like/reaction and get 25$
Next 10 submissions with the most likes/reactions also wins 10$ each
#Giveaway#MiniGame#Partnership#Web3
KardiaChain Socials :
🌐Website | 🐦Twitter |🌐Community | 🌐Channel
☑️Disclaimer: Please do your own research before joining to any project.
Do you want to learn more about #KAIDEX x Ameta? 📣
Join the KAHOOT Mini Game for a chance to Learn & Earn a reward pool of 100$ in $APLUS!
Quiz starts on 01:00 PM UTC, 3rd Oct 2022 onJoin Now
Kahoot link soon 👀
TOP 5 winners will receive 20$ of APLUS each 💰🤑
#MiniGame#Giveaway#Airdrop $KDX
Disclaimer: Please do your own research before joining to any airdrops project, also airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens. Just join airdrop for free!
✅✅✅✅#Official KuCoin and TON Present Frog Trader #Minigame on Telegram! 🤩 Brought to you by KuCoin, a leading global crypto exchange trusted by one in four crypto holders worldwide! #Get Upto 2 lack coins
🐸 Welcome reward of 10K Frog Coins! join fast guys :- https://t.me/xkucoinbot/kucoinminiapp?startapp=cm91dGU9JTJGdGFwLWdhbWUlM0ZpbnZpdGVyVXNlcklkJTNEMTA0ODM5NjMwMSUyNnJjb2RlJTNEUUJBWkdRQUs=
➖ Click on bot
➖ Check your telegram age
➖ Link your kucoin exchange account
➖ Connect telegram wallet only
➖ Premium users will get 50k
#Note :- Don't skip #early users will get more benefits join fast before end
📈
🐹Solution for the new mini-game in
Hamster Kombat
👉https:://t.me/hamster_kombat
📣Stay updated! Subscribe to our channel:
⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️
#hamsterkombat#hamster#kombat#key#btc#combo#hamsterkey#minigame#game#clicker#taptap#memecoin