Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
😄Paint
➖➖➖➖➖➖
🔘 The noun paint refers to coloured liquid that makes things look nice. The verb has different meanings. It can mean to put paint on something with a brush.
🔜 I'm going to paint this wall yellow, and this one white.
🔜The table was painted green.
🔘 Paint can also mean to make a picture of something, using paint.
🔜 She painted a portrait of me, it looks great.
🔜 The artist painted the beautiful landscape.
🔘 Paint can also mean to apply a liquid (not just paint) to something with a brush.
🔜 Paint the pastry with egg before putting it in the oven.
🔜 Paint the wood preserver on the fence to protect it.
#Paint👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys
😄Paint
➖➖➖➖➖➖
🔘 The noun paint refers to coloured liquid that makes things look nice. The verb has different meanings. It can mean to put paint on something with a brush.
🔜 I'm going to paint this wall yellow, and this one white.
🔜The table was painted green.
🔘 Paint can also mean to make a picture of something, using paint.
🔜 She painted a portrait of me, it looks great.
🔜 The artist painted the beautiful landscape.
🔘 Paint can also mean to apply a liquid (not just paint) to something with a brush.
🔜 Paint the pastry with egg before putting it in the oven.
🔜 Paint the wood preserver on the fence to protect it.
#Paint👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys