Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Мир продолжает понемногу отходить от массового зеленого умопомрачения. General Motors готовится представить новые двигатели V8, в разработку вложили почти $1 млрд.
Появится сразу два агрегата, 5,7 и 6,6 литра. Первый для таких моделей, как Chevrolet Silverado 1500. Второй – для ряда Corvette. Обещают, что они будут не простыми большими, а большими и технологичными.
По крайней мере в США выбор не будет ограничен перекрученными 2-х литровыми моторами.
#v8
🚗✨Maserati Unveils the Final Quattroporte with V8 – Grand Finale!🎉
This stunning vehicle, custom-made for a client in the USA, showcases a unique and exquisite design. 🌟🇺🇸 With the V8 engine now retired from the lineup, including the Ghibli sedan and Levante SUV, this masterpiece marks the end of an era.
A true symbol of luxury and performance! 🏁💎
#Maserati#Quattroporte#V8#GrandFinale#LuxuryCars#Auto🚘💖
🚗💨 Exciting news from Lamborghini! The upcoming Lamborghini Temerario is set to unleash over 1000 horsepower! 🔥
Ruwen Mor, a former Audi engineer now at Lamborghini, revealed that the power of the V8 engine could increase from 200 to around 220 hp per liter. Plus, the car will feature three electric motors for an extra boost! ⚡️
The Temerario follows in the footsteps of the iconic Huracan, which had a naturally aspirated V10 engine with a peak output of 640 hp. While a V6 could have delivered even more power, the decision was made to stick with a higher cylinder count to meet customer expectations. 💪
#Lamborghini#Temerario#Supercar#1000HP#V8#ElectricPower#CarEnthusiast#LuxuryCars#Auto