Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🐄🐄 𝘿𝙄𝙂𝙀𝙎𝙏𝙄𝙊𝙉 𝙄𝙉 🐄𝙍𝙐𝙈𝙄𝙉𝘼𝙉𝙏𝙎 🐄🐮
👉All herbivores (plant-eating mammals) are called ruminants.
👉They rechew the cud to break down plant matter and stimulate digestion.
👉The stomach is divided into four chambers- rumen, reticulum, omasum, and abomasum.
🐄🐮 𝙋𝙧𝙤𝙘𝙚𝙨𝙨 𝙊𝙛 𝘿𝙞𝙜𝙚𝙨𝙩𝙞𝙤𝙣 🐄🐮
👉Ruminants quickly swallow the food and store it in the rumen.
👉Once the rumen is filled, food is passed into the second chamber (reticulum).
👉In the reticulum, digestive juices partially digest the food.
👉Partially digested food is called cud.
👉Now when mammals are resting, bring the cud back into the mouth for rechewing.
👉After cud is chewed food is passed to the omasum and the abomasum.
👉Symbiotic bacteria in the caecum brought complete digestion of cellulose.
#digestion
https://t.me/starvetbooks