Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#from#beautiful
A mother and a child on a wooden horse photo, in the style of gritty urban realism, new american documentary photography, mixed media installations, cheyenne art, rural life depictions, colorized, suburban ennui capturer --ar 103:128 --v 6.0
✅pitpeterssen _Midjourney v6.0
🚀Boost this Channel
@ai_artz🌿
#from#beautiful
Beautiful indian woman flying up in the sky with her aircraft chair, clouds moving in full speed, woman streching her hands on clouds, her hair also flying in speed, minimal, shot with Sony Alpha with wide angle lens, 16k, candid, aperture F1.2, full detail shot, dramatic lighting, --ar 16:9
✅ Vinaysaya _Discord
@ai_artz
#from#beautiful
Portrait and fashion photography: a combination of renaissance costumes and snowflakes, texturing, ::elegant clothes worn by the most beautiful women, a woman with a wonderful face and expressive eyes, beautiful delicate makeup, the highest quality, translucent floral fabrics, simple and aesthetic hairstyles, dynamic poses, neutral interesting dark background, award winning fashion photography, photorealistic, bright, elegant, golden ratio, elite, highly detailed, color triad, dynamic composition, ultra resolution, ultra wide shot, digital art, world made of light, soft lighting, unreal engine, depth of field 8k, full hd photo, HDR, high resolution photography, macro photography, beautiful highlights, zbrush art, photoshop, studio setting, simple, neutral, grainy, matte, fashion style :: Canon EOS 5D Mark IV EFL 100mm, f /1.4, ISO 50, 1/100 sec, Eye Sharpness, RAW, v4 - a r 2:3 - 800 sec, Chaos 49
✅ Adora _Discord
@ai_artz
#from#beautiful
An underwater urbex guerilla garden with old cars on the shoal underwater ::directional light, cinematic, alcohol ink and cinematic, saudek and sorayama ::hyperrealistic --ar 3:2 --q 2 --upbeta --s 750 --v 5.1
✅ Prima Demonessa _Discord
Join us for more @ai_artz
#from#beautiful
Gouache painting of a book-nook diorama of a cryptid conservatory, has incredible attention to detail, intricate, highly detailed, fantastic realism, fantasy, magical, led lights, --q 2 --s 750
✅ Adriann _Discord
@ai_artz
#from#beautiful
Photography of the living room of a huge hotel on Mars, futuristic Hotel on Mars furnished in japanes style, 8k, photo realistic, beautiful japanese design, welcoming Hotel, ultra realistic, ultra detaile
✅ Max05 _Discord
@ai_artz