Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🪐 Scientists using the Green Bank Telescope detected a persistent radio signal from Proxima Centauri, the closest star to our Sun, sparking interest due to its unusual nature. Although later studies found the signal was most likely caused by human technology, Proxima Centauri remains a key target in the search for alien life because it hosts the potentially habitable planet Proxima b. ✨
#aliens⚡#exoplanets⚡#proximacentauri⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The SETI Institute's ongoing Breakthrough Listen project regularly targets the region around the star Proxima Centauri—our solar system’s closest neighbor—searching for unusual radio signals that could hint at alien technology. By scanning billions of radio frequencies from Proxima Centauri and other nearby stars, scientists are using real astronomy to explore whether advanced extraterrestrial civilizations might exist within our interstellar neighborhood. ✨
#aliens⚡#ProximaCentauri⚡#SETI⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The future of interstellar travel may hinge on new propulsion ideas being studied today, like nuclear electric propulsion—which uses nuclear reactors to generate electricity for ultra-efficient ion engines. NASA has tested this kind of technology in missions like Deep Space 1, and scientists hope that one day, such systems could send spacecraft toward distant stars like Proxima Centauri far faster than chemical rockets ever could. ✨
#spaceships⚡#propulsion⚡#ProximaCentauri⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Scientists are investigating laser-driven spacecraft, where powerful laser beams from Earth could propel tiny probes at speeds up to 20% that of light—fast enough to reach Proxima Centauri, our closest neighboring star system, in just over 20 years. This approach, known as "light sail" propulsion, uses intense light pressure against a thin, reflective sail to accelerate a probe, offering a glimpse of how interstellar journeys could become possible within a human lifetime. ✨
#spaceships⚡#ProximaCentauri⚡#lightsail⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The challenge of reaching other star systems like Proxima Centauri, over 4 light-years away, drives scientists to explore futuristic spaceship concepts beyond anything in use today. One promising idea is fusion propulsion, which would harness the power of fusing atomic nuclei—just like in the Sun—to generate immense thrust, potentially making journeys to nearby stars possible in a matter of decades rather than millennia. ✨
#fusion⚡#propulsion⚡#spaceships⚡#ProximaCentauri⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels