Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
⚡️Soat 19:00 da Premyera, YouTube kanalimizga obuna bo'lib qo'ying!
Kanal: 👉https://www.youtube.com/@SEEYOUZBEKISTAN/videos
#QuyoshPechi#Interstellar
@seeyouzbekistan • O’zbekistonni biz bilan kashf eting!
🌎 Exploring the edge of the solar system, NASA’s Voyager 1 spacecraft became the first human-made object to enter interstellar space in 2012. It carries instruments to measure cosmic rays, magnetic fields, and particles beyond the Sun’s influence—data still transmitted from over 24 billion kilometers away. ✨
#space⚡#voyager⚡#interstellar
👉subscribe Interesting Planet
👉more Channels
🪐 Some of the most mysterious worlds in our galaxy are rogue planets like CFBDSIR J214947.2-040308.9, a giant planet drifting alone in interstellar space without a star to orbit. Detected about 130 light-years from Earth, this lonely world glows with leftover heat from its birth and is studied in infrared light, revealing that even without a sun, planets can wander the dark, silent stretches between stars. ✨
#rogueplanets⚡#interstellar⚡#giantplanets⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The interstellar probe mission concept led by NASA aims to send a spacecraft beyond our solar system, much farther than Voyager 1, to distances over 1,000 astronomical units (AU) from the Sun. This ambitious plan would explore the uncharted space between stars and gather data about the outer regions of our solar system and the nearby interstellar environment, including the edge where the solar wind from our Sun blends into the thin gas found between stars. ✨
#interstellar⚡#travel⚡#NASA⚡#exploration⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 1977, the Voyager 2 spacecraft was launched carrying a special message for any potential alien civilizations—a Golden Record encoded with music, greetings in 55 languages, and sounds from Earth. Voyager 2 is now over 20 billion kilometers from our planet, traveling beyond the edge of the solar system and continuing its silent journey through interstellar space. ✨
#aliens⚡#voyager⚡#interstellar⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 1977, the Voyager 1 spacecraft left Earth carrying a "Golden Record"—a carefully crafted message with sounds and images from our planet, designed in the hope that someday it might be found by aliens in another star system. Now Voyager 1 is more than 24 billion kilometers away, continuing its silent journey through interstellar space, making it humanity’s most distant attempt to reach out to any extraterrestrial civilization. ✨
#aliens⚡#voyager⚡#interstellar⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 NASA and ESA are collaborating on future missions to develop solar sail technology—a method that harnesses sunlight for propulsion—to power lightweight spacecraft toward nearby stars like Alpha Centauri. Unlike rockets, solar sails use the gentle push of photons (tiny particles of light) from the Sun to gradually accelerate, making it possible for small probes to reach interstellar space without carrying any fuel onboard. ✨
#spaceships⚡#interstellar⚡#solar⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The future of interstellar travel could be shaped by the use of atomic clocks and navigation systems like NASA's Deep Space Atomic Clock, tested aboard the Earth-orbiting DSAC mission. Ultra-precise atomic clocks allow spacecraft to autonomously navigate across billions of kilometers, setting the stage for robotic probes to travel to distant stars such as Alpha Centauri and safely communicate their position back to Earth. ✨
#interstellar⚡#technology⚡#navigation⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The future of interstellar travel could be shaped by experiments like NASA's Heliospheric Imager, which studies the vast region where the Sun's solar wind meets interstellar space—the heliopause. By understanding this distant boundary zone, where Voyager 1 crossed over 120 astronomical units from the Sun, scientists are learning how future spacecraft might navigate safely beyond our solar system and toward other stars like Alpha Centauri. ✨
#interstellar⚡#heliopause⚡#voyager⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels