Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Пока в нескольких регионах РФ проходят испытания гибридные трактора Zoomlion DV3354, на Ленинградской земле испытывали трактор PG2004 с Немецкой полуавтоматической трансмиссией PowerShift (ZF).
Работа с плугом Kverneland PN100-5 (5 корпусов)на тяжелых почвах.
Глубина обработки 30 см
Скорость 8-9 км/ч
На глубине 20-25 см
Скорость 10-11 км/ч
Работа с тяжелым дискатором (5800 кг)
Диаметр дисков 660 мм.
Глубина обработки 12 см
Скорость 10-12 км/ч
С поставленными задачами трактор Zoomlion PG2004 справился, отмечено что потребление топлива значительно меньше в сравнении с механическими трансмиссиями, выше производительность и комфорт механизатора!
#Агромаг#испытания#демо#Zoomlion@Zoomlion_AG_Rus#PG2004#ZF#PowerShift#лучшийтрактор#Kverneland
Забудьте про ручное переключение!
С трансмиссией от мирового производителя ZF установленной на PG2004 вы получите плавность управления и точность, которые делают каждый проход по полю эффективным. Мягкая смена скоростей не только экономит ваше время, но и снижает утомляемость, позволяя работать с максимальной отдачей.
Трактор Zoomlion PG2004 — это трактор с мощностью 200 л.с. и оснащенный передовыми технологиями, которые минимизируют расход топлива, что снижает эксплуатационные расходы.
Zoomlion PG2004 — европеец в Китайской шкуре!
🌟🌟🌟Если у Вас есть потребность в таком тракторе, мы готовы предоставить его для Вас на демо испытания!🌟🌟🌟
За дополнительной информацией обращайтесь в отдел продаж +79006331826
#Агромаг#лучшийтрактор#демо#испытания#технологии#PG2004#ZoomlionPG2004#китайскийтрактор#ZF#европеец
https://x.com/zachqfish/status/2053461293190062283?s=52
🙏 Why We Cannot See Creator
Sometimes people ask, “Why can’t we see Creator?”
It’s a beautiful question, and one that has echoed through humanity since the beginning of time.
Maybe the answer is simpler than we think.
A child in the womb cannot see its mother.
It cannot comprehend the world beyond the walls that surround it. It does not know who is feeding it, protecting it, or sustaining every breath and heartbeat. And yet, the mother is there the entire time... loving, nourishing, and holding that child in perfect care.
The child may not understand the mother, but the mother understands the child completely.
In many ways, we are no different.
We live inside a vast and mysterious universe, surrounded by intelligence, beauty, and order far beyond what our minds can fully grasp. We may not be able to see Creator with our physical eyes, but we can witness the fingerprints of Creator everywhere... in the rhythm of our hearts, the precision of nature, the power of love, and the quiet inner knowing that reminds us we are never alone.
Perhaps this life is a sacred womb.
A place where our souls are growing, learning, and preparing for a greater birth into a reality we cannot yet imagine.
And just like the child in the womb, we may not fully understand what holds us.
But we are held.
We are guided.
We are loved beyond measure.
One day, when the veil lifts and our awareness expands, we may realize that what we were searching for was never separate from us.
Creator was not hidden.
Creator was carrying us all along.
ZF 🔥
#Creator#Faith#SpiritualAwakening#TheWayOfBeing#DivinePresence#Awakening#Consciousness#NewEarth#TrustTheJourney#ZF🔥