Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🌎 The invention of the safety elevator by Elisha Otis in 1852 made skyscrapers possible. His design featured a locking mechanism that stopped the elevator if the hoisting cable snapped. Otis demonstrated this life-saving device at the 1854 World’s Fair in New York, boosting public trust in elevators. ✨
#inventions⚡#history⚡#engineering
👉subscribe Interesting Planet
👉more Channels
🌎 X-rays were discovered accidentally in 1895 by German physicist Wilhelm Röntgen. While experimenting with cathode rays, he noticed an unknown radiation that could pass through solids and reveal images of bones. Today, X-rays are a key tool in medicine and industry worldwide. ✨
#inventions⚡#history⚡#physics
👉subscribe Interesting Planet
👉more Channels
🌎 The invention of the modern stethoscope in 1816 by French physician René Laennec transformed medical diagnosis. By rolling paper into a tube, Laennec could hear internal chest sounds clearly, improving detection of lung and heart conditions. The first stethoscopes were made of wood and about 25 centimeters long. ✨
#history⚡#medicine⚡#inventions
👉subscribe Interesting Planet
👉more Channels
🌎 In 1867, Swedish chemist Alfred Nobel invented dynamite by stabilizing volatile nitroglycerin with an absorbent clay called kieselguhr. This made blasting much safer for construction and mining. Nobel later used his dynamite fortune to establish the Nobel Prizes in 1895. ✨
#inventions⚡#chemistry⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 In 1903, the Wright brothers achieved the first powered, controlled, and sustained flight of an airplane at Kitty Hawk, North Carolina. Their aircraft, the Wright Flyer, flew for 12 seconds and covered 36 meters. ✨
#inventions⚡#aviation⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 The accidental invention of safety glass happened in 1903, when French chemist Édouard Bénédictus dropped a glass flask coated with plastic cellulose nitrate. Rather than shattering, the glass cracked but held together, inspiring shatter-resistant windshields. By 1927, safety glass became standard in automobile manufacturing. ✨
#inventions⚡#chemistry⚡#history
👉subscribe Interesting Planet
👉more Channels
The first vending machine was invented in the 1st century AD by Greek engineer Heron of Alexandria. It dispensed holy water when a coin was inserted—the weight tilted a lever, opening a valve to release water before the coin dropped. 💧⚖️
[Learn more]
@googlefactss
#History#Inventions#Engineering#AncientGreece
Professor Muhammed Uvaze ixtirolari Buyuk Britaniyada patentlashtirilgani haqida Hudud informatsion dasturida lavha tayyorlandi.
#hudud#patent#inventions
⬇️Biz ijtimoiy tarmoqlarda:
Veb-sayt | Telegram | Instagram | Facebook
🌎 The discovery of radioactivity in 1896 by Henri Becquerel revealed that uranium salts emit invisible energy. This led to the identification of new elements like polonium and radium by Marie and Pierre Curie. Their work contributed to the development of X-ray machines and atomic science. The Curies isolated just 1 gram of radium from 8 tons of ore. ✨
#radioactivity⚡#discovery⚡#inventions
👉subscribe Interesting Planet
🌀💦 South African Invention That Changed Pool Life
Did you know the automatic pool cleaner was invented in 🇿🇦 South Africa?
👨🔧 In 1974, hydraulics engineer Ferdinand Chauvier (pictured), who had moved from the Belgian Congo to South Africa, came up with a way to take the hassle out of pool cleaning.
The result? The legendary Kreepy Krauly — one of the very first automatic pool cleaners, designed and built in Springs, South Africa. 🌍✨
His invention made pools around the world easier to maintain — and became a proudly South African contribution to everyday comfort.
🏊♂️ From Johannesburg to Los Angeles, millions of pools have been cleaned thanks to Chauvier’s idea.
#Inventions#SouthAfrica#Innovation#KreepyKrauly#History#MadeInSA