Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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 studying the future of interstellar travel are exploring how hydrogen harvested from interstellar space—called "ramjet" propulsion—could one day fuel journeys to stars like Alpha Centauri, located over 4 light-years from Earth. A concept known as the Bussard Ramjet proposes using a huge electromagnetic field to collect hydrogen atoms as a spaceship speeds through space, fusing them for energy in the same way stars do, potentially enabling continuous acceleration across vast cosmic distances. ✨
#spaceships⚡#technology⚡#AlphaCentauri⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the double star system Alpha Centauri, light from one star to the other takes over 20 hours to cross the distance—showing that even within a “nearby” solar system, the speed of light sets a hard limit for communication and travel. This demonstrates how vast even the smallest cosmic neighborhoods really are, as light’s top speed of 299,792 kilometers per second still can't make interstellar distances feel quick. ✨
#speedoflight⚡#alphacentauri⚡#spacedistances⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Traveling to other stars is one of humanity’s greatest challenges, as even the nearest star system, Alpha Centauri, is over 4 light-years away—about 40 trillion kilometers! Current spacecraft, like Voyager 1, are only just leaving our solar system after more than 45 years, showing that interstellar travel will require new technologies, possibly using powerful methods such as nuclear propulsion or solar sails—giant, ultra-thin mirrors that ride the pressure of sunlight across space. ✨
#interstellar⚡#travel⚡#technology⚡#AlphaCentauri⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The Breakthrough Starshot project is testing how ultra-light spacecraft powered by laser-driven lightsails could one day reach Alpha Centauri, our nearest star system, in just a few decades. These tiny probes, traveling at a fraction of the speed of light (over 100 million kilometers per hour), would gather data from planets like Proxima Centauri b, showing how future interstellar journeys might become possible using cutting-edge technology and real astronomical targets. ✨
#interstellar⚡#travel⚡#AlphaCentauri⚡#lightsail⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Scientists testing the future of interstellar travel are examining how giant particle accelerators in space could launch tiny probes to neighboring star systems like Alpha Centauri. By using electromagnetic fields to give miniature spacecraft a massive boost, this method could send probes racing out of the solar system much faster than traditional rockets, all powered by technologies already proven in facilities like CERN's Large Hadron Collider on Earth. ✨
#interstellar⚡#travel⚡#AlphaCentauri⚡#particleaccelerators⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels