Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
"I'm rose without it's essence,
I'm a bouquet of autumn leaves,
I'm a tree without it's texture,
I'm glass without it's fragility,
I'm a sidewalk without grafitti,
A plain white coral,
I'm a scenery without a painter,
You see;
I still exist without you,
But It's not beautiful..."
#review#nilu
🔥 Дизайнер Александр Селипанов, основавший автомобильный бренд Nilu27, рассекретил суперкар Nilu
Интерьер — смесь минимализма и футуризма. Физических кнопок практически нет — лишь на потолке имеются переключатели в авиационном стиле. При этом тачскринов в салоне суперкара тоже нет: единственный дисплей встроен в зеркало заднего вида.
Базируется автомобиль на углепластиковом монококе с трубчатыми подрамниками, имеет полностью независимую подвеску и 21-дюймовые колёсные диски с карбон-керамическими тормозами Brembo с шестипоршневыми суппортами.
Атмосферный 6,5-литровый V12 развивает 1070 л.с. и 860 Нм, что позволяет разгоняться до максимальных 400 км/ч и набирать первую сотню быстрее чем за 3 секунды.
Полноценная премьера состоится 15 августа. Сначала сделают 15 машин для гоночных трасс, а уже потом выпустят 54 купе для дорог общего пользования.
@avtoNovosti
#новинки#суперкар#Nilu
🔥 Designer Alexander Selipanov, who founded the car brand Nilu27, has declassified the Nilu supercar
The interior is a mix of minimalism and futurism. There are practically no physical buttons - only on the ceiling there are switches in aviation style. At the same time, there are no touchscreens in the interior of the supercar either: the only display is built into the rearview mirror.
The car is based on a carbon fiber monocoque with tubular subframes, has a fully independent suspension and 21-inch wheels with Brembo carbon-ceramic brakes with six-piston calipers.
Atmospheric 6.5-liter V12 develops 1070 hp and 860 Nm, which allows to accelerate to a maximum of 400 km/h and gain the first hundred faster than 3 seconds.
The full-fledged premiere will take place on August 15. First, 15 cars will be made for race tracks, and then 54 coupes for public roads will be released.
@CarsNews
#new#supercar#Nilu
🚗✨Introducing the Nilu Supercar by Alexander Selipanov!🔥
Designed for true driving enthusiasts, the Nilu is a masterpiece that strips away unnecessary electronics to deliver pure driving pleasure. 🏁💨
🔩Powerful Performance:
Equipped with a breathtaking atmospheric V12 engine producing 1070 hp, paired with a 7-speed manual transmission. This beast can reach a top speed of 400 km/h and accelerate from 0 to 100 km/h in under 3 seconds! ⚡️
⚙️Cutting-Edge Engineering:
Built on a carbon fiber monocoque with tubular subframes, featuring fully independent pushrod suspension and 21-inch wheels with carbon-ceramic brakes. 🛠️
🚢Exclusive Release:
Only 15 units will be produced for track enthusiasts, followed by another 54 road-ready models. Pricing details remain under wraps! 💰
#Nilu#Supercar#AlexanderSelipanov#DrivingPassion#V12#Auto