Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Hacker AI
Provides advanced AI and integrated tools to help security teams conduct comprehensive penetration tests effortlessly. Scan, exploit, and analyze web applications, networks, and cloud environments with ease and precision, without needing expert skills.
🔗 Links:
- Website
- Source code
❤️ Support the Project
If this project makes your life easier, here are a few quick ways to show some love:
⭐ Star the repo/app
☕ Buy a coffee for the developer
🛠 Contribute code, issues, or pull-requests
🏷 Tags: #AI#Website
🔥 DeckForge Official Website is LIVE!
Our official website is now online — the first step toward building a full digital home for the entire DeckForge community.
👉https://play.deckforge.net/
Over the coming weeks, we’ll be expanding it with new sections, guides, lore, developer updates, partner announcements & exclusive content that will grow together with the game and our universe.
More updates are coming. Stay Forged!
#DeckForge#Website#OpenBeta
Join the DeckForge Community:
🌐YouTube𝕏Twitter🎮Discord
👉Chat👉Announcements👉DeckForge