Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🎉 Exciting Partnership Announcement
We're thrilled to introduce our first official partner for the SingSing SocialFi SDK: Cowtopia🐮!
Cowtopia, an innovative farming simulation game, will be the first to integrate our powerful SocialFi SDK. This collaboration marks a significant milestone as we prepare to revolutionize the Telegram mini-app ecosystem.
Stay tuned and see how Cowtopia will utilize our SDK to create an immersive and socially connected gaming experience.
Read more and open treasure at: X Post
#SingSingSDK#Cowtopia#TelegramGaming#SocialFi#FarmingSimulator#ComingSoon
🔥🎉 Prepare yourself for an unparalleled gaming experience with TonAge! 🎮
💥
😀
💯Bid farewell to losses and say hello to an assured 100% Return to Player (RTP) in TonAge! 💰
✨
😀⭐️ Launch into a world of electrifying gameplay, where each spin, move, and quest is brimming with exhilarating excitement!
💥📍
⚡️
😀 Driven by blockchain technology, TonAge guarantees fair play and transparent outcomes, ensuring you can game with absolute peace of mind! 😎
😀
💎
✨ Unlock legendary treasures, conquer epic challenges, and witness your virtual victories transform into real-world value with the TON cryptocurrency! It's the ultimate gaming revolution!
🎁
💎
🤝⭐️ Join a vibrant community of gamers, strategists, and treasure seekers from all corners of the globe. Share tips, challenge friends, and compete for the top position on the leaderboard! 📍
🎁Don't miss out on this groundbreaking opportunity! Embark on an adventure that guarantees 100% RTP and endless thrills!
💎https://bit.ly/3SlL8fq
#TonAge#TelegramGaming#100PercentRTP#BlockchainGaming#EarnTON