Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
♻️FEEDING GUIDE ON BROILER CHICKS
✅Starter Feed (0-3 weeks):
The starter feed is designed to provide the energy and
protein necessary for rapid growth during the first few
weeks of a broiler's life. It's typically higher in protein content
to support muscle and feather development.
✅Here's a typical formulation for starter feed:
Maize (Corn): 50-60% — Provides energy.
Soybean Meal: 25-30% — Rich in protein for growth.
Fish Meal/Meat Meal: 5-10% — Additional protein to boost
growth.
Wheat Bran: 5% — Source of fiber and micronutrients.
Limestone: 1-2% — Ensures proper bone development.
Dicalcium Phosphate: 1-2% — Provides phosphorus and
calcium for bone health.
Salt: 0.2-0.3% - Maintains electrolyte balance.
Vitamin and Mineral Premixes: As per manufacturer's
guidelines for the required nutrients.
Probiotics and Enzymes: 0.5-1% — Improves digestion and
nutrient absorption.
✅Grower Feed (3-6 weeks):
The grower feed formulation is slightly lower in protein than
the starter feed but still maintains enough protein to support
continued growth and muscle development.
♻️Typical grower feed formulation:
Maize (Corn): 55-65% — Provides energy for continued
growth.
Soybean Meal: 20-25% — Protein for muscle development.
Sunflower Meal: 5-10% — Additional protein source and
enhances digestibility.
Rice Bran: 5-10% — Provides energy and fats for increased
growth rate.
Wheat Bran: 2-5% — Fiber for digestion.
Limestone: 1-1.5% — Calcium for bone health.
Dicalcium Phosphate: 1-1.5% - Balanced phosphorus and
calcium.
Salt: 0.2-0.3% — Electrolyte balance.
Vitamin and Mineral Premixes: According to manufacturer
guidelines.
Probiotics and Enzymes: 0.5-1% — Support gut health and
nutrient absorption.
♻️Finisher Feed (6 weeks until market):
The finisher feed focuses on providing the final boost in
weight gain and ensures that broilers reach market weight
efficiently. It contains less protein than the grower feed, as
the chickens are now focusing more on fat deposition
#Dr.Amanuel
https://t.me/starvetbooks