Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Tata Power Renewable Energy Limited (TPREL) received board approval to invest ₹6,500 crore to establish a 10 GW photovoltaic ingot and wafer manufacturing facility. The project will be developed in two phases of 5 GW each, likely at a greenfield site in Nellore, Andhra Pradesh, with an estimated payback period of five years. This strategic expansion into upstream manufacturing allows Tata Power to achieve backward integration, significantly reducing reliance on Chinese imports while aligning with India’s ALMM framework to strengthen the domestic solar supply chain.
Source
#MakeInindia#solar
Andhra Pradesh Chief Minister N Chandrababu Naidu will lay the foundation stone for ReNew Energy Global plc's Rs 5,400 crore solar manufacturing facility in Anakapalli district. This 6 GW solar ingot and wafer unit marks a significant step in India's push for domestic clean energy manufacturing and energy security, aligning with the state's Integrated Clean Energy Policy 2024
Source
#MakeInindia#solar
🌎 Pluto, once called the ninth planet, orbits in the distant Kuiper Belt and takes about 248 Earth years to complete one orbit around the Sun. ✨
#planets⚡#astronomy⚡#solar-system
👉subscribe Interesting Planet
👉more Channels
🌎 Jupiter’s Great Red Spot is a giant storm larger than Earth and has been raging for at least 350 years, swirling powerful winds nonstop across the planet’s atmosphere. ✨
#planets⚡#astronomy⚡#solar
👉subscribe Interesting Planet
🌍 On rare occasions, the aurora can be seen far from the poles, reaching as far south as Texas or southern Europe during strong solar storms. Their shifting shapes can move faster than a cheetah runs. ✨
#aurora⚡#atmosphere⚡#solar⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Earth travels around the Sun at nearly 30 kilometers per second. This speedy journey means our planet covers more than 940 million kilometers every year as it orbits through space. ✨
#Earth⚡#orbit⚡#solar⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
Japan is home to 73 of world's 100 largest floating #solar plants they prevent water evaporating, and help secure reservoirs in water-stressed countries. - #Japan#Naturehttps://twitter.com/i/status/1391177362927198211@LovelyNature
Japan is home to 73 of world's 100 largest floating #solar plants they prevent water evaporating, and help secure reservoirs in water-stressed countries. - #Japan#Naturehttps://twitter.com/i/status/1391177362927198211@OnlineEducation10
🪐 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