Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🐍During this festive season of the #LunarNewYear, the entire CyberCharge team wishes you a Happy Year of the Snake!
May this year bring prosperity and joy to you and your loved ones 🫂
Thank you for your continued support, helping us grow and achieve incredible milestones.
We're just getting started! 🚀
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
Dear friends,
Warm greetings on the occasion of #LunarNewYear!
We wish you good health, happiness and prosperity! May this upcoming year bring along success and great fortune for you and your families.
Sincerely yours,
Russian Mission to #ASEAN
Bringing good luck and prosperity into the new year with the power of red! From lanterns 🏮 to envelopes 🧧, red is a traditional color of #ChineseNewYear. Don't forget to add a touch of red to your celebrations for a prosperous.
Принося удачу и процветание в новый год силой красного! От фонарей до конвертов, красный является традиционным цветом #ChineseNewYear. Не забудьте добавить нотку красного к своим празднованиям для процветающего.
#LunarNewYear#wallpaper
🧧 Follow 🧧@PeachLovesGoma🧧
Wish everyone a happy Lunar New Year! Bring glory back to Hong Kong in the year of dragon!
#HKDMovement
#glorytoHongKong
#lunarnewyear
#standwithhongkong