Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🪐 Near the center of the Small Magellanic Cloud, scientists have discovered a magnetar called SXP 1062 with a magnetic field so strong it can reshape atoms and trigger intense X-ray outbursts. Magnetars are a rare kind of neutron star—ultra-dense remnants of exploded massive stars—whose magnetic fields are trillions of times stronger than Earth's and can even change the properties of empty space around them, making these cosmic magnets among the universe's most extreme phenomena. ✨
#magnetars⚡#neutronstars⚡#spacefacts⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The star VY Canis Majoris, located about 3,900 light-years from Earth, is one of the largest known stars in the universe—so huge that if placed at the center of our solar system, its surface would reach beyond the orbit of Jupiter. This red hypergiant loses mass at an incredible rate, creating vast clouds of dust and gas that make it appear as a dim, shifting patch in telescopes rather than a sharp point of light. ✨
#unusualstars⚡#hypergiants⚡#spacefacts⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the spiral galaxy Messier 81, astronomers use precise observations of variable stars called Cepheids to confirm that light travels at a constant speed—299,792 kilometers per second—across millions of light-years. By timing the changes in these stars' brightness, scientists can measure vast intergalactic distances, showing that the universal speed limit of light holds true even when crossing the immense gulf between galaxies. ✨
#speedoflight⚡#Messier81⚡#spacefacts⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
The Moon takes about 29.5 Earth days to go from one sunrise to the next. Daylight lasts around 14.75 days, and night also lasts about 14.75 days. This long day and night happen because the Moon spins slowly and moves around Earth at the same time. We always see the same side of the Moon because of this. 🌕🌑
[Read more]
@googlefactss#Moon#LunarDay#SpaceFacts#Astronomy
The 1967 Outer Space Treaty says no country can own the Moon, but rules about mining are still unclear. Working on the Moon could also be dangerous for human health.
The Moon has water ice and rare metals that could help future space missions. But mining the Moon will damage its surface and spread potentially harmful dust. 🌕🚀
[Read more]
#MoonMining#SpaceLaw#OuterSpaceTreaty#SpaceFacts@googlefactss
During Apollo 10, a piece of poop floated inside the spaceship. The astronauts al denied it was theirs. In zero gravity, everything floats. 🚀💩
@googlefactss
#Apollo10#SpaceFacts#ZeroGravity#Astronauts#SpaceHistory
Pluto is slightly bigger than Russia.
Pluto has a surface area of about 17.65 million km².
Russia has an area of about 17.1 million km².
Some sources say otherwise because of old measurements or rounding.
Those sources are wrong.
🪐🌍📏
[Source 1]
[Source 2]
@googlefactss
#Pluto#Russia#SpaceFacts#Geography#NASA#Science#planet#dwarfplanet