Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#javascript#hacktoberfest#stremio
Stremio is an easy-to-use media center app that lets you find, watch, and organize movies, TV shows, live channels, and more from many sources in one place. You can install addons to add content, sync your library across devices, and even download videos for offline viewing. It supports subtitles, Chromecast streaming, and high-quality formats like 4K HDR. Stremio keeps your data safe by running addons remotely and respects your privacy with minimal data collection. This means you get a secure, convenient, and personalized streaming experience without switching apps or worrying about security.
https://github.com/Stremio/stremio-web
Stremio
Freedom To Watch Everything You Want
Stremio is a modern media center that's a one-stop solution for your video entertainment. You discover, watch and organize video content from easy to install addons. Movies, TV shows, live TV or web channels - find all this on Stremio.
Features:
• Multi-platform support
• Discover new content with ease
• Extendable video catalogue
• All of your video content on one screen
• Organize your video library
• Keep track of everything you watch
• Cast to another device
• Watch video from many different sources
• Play HTTP links and torrent files
Download: https://www.stremio.com/downloads
https://github.com/Stremio
⚠️ Not fully foss?
#Stremio#movies
@foss_desktop