Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Girls’ Meeting at Green University!
✅On October 23, a special gathering was held for our female students, focusing on etiquette, moral values, and personal growth.
🔄The event also featured a psychological training session that helped participants build confidence and strengthen communication skills.
#GreenUniversity#StudentLife#GirlsMeeting#PersonalDevelopment
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
📖Title : This Too Shall Pass
✍️Author : Julia Samuel
⭐️Rating : 3.72/5 (Goodreads)
📆Published : Mar 05, 2020
————————————————
Summary:This Too Shall Pass by Julia Samuel is a profound exploration of how humans cope with change and emotional upheaval. Drawing on her extensive experience as a psychotherapist, Samuel presents twelve moving and deeply personal case studies that cover themes such as grief, relationships, identity, and trauma. Each story reveals how people struggle with, resist, and ultimately adapt to change. Through compassionate storytelling and psychological insight, Samuel illustrates that while change is inevitable and often painful, it also offers opportunities for growth and healing. The book is a comforting, insightful guide for anyone navigating life’s unpredictable transitions and emotional challenges.
————————————————
#nonfiction#psychology#selfhelp#personaldevelopment@Bookslibraryofficial@free_novellas@the_ancient_library
Diversity & Inclusion
There is a significant relationship between competitive profit gains and diversity.
Companies with gender, ethnic and racial diversity are at least 15 percent more likely to experience above-average financial returns.
#Wednesday#Day-3
#personalDevelopment#selfhelp#leadership#Growth#Teambuild
Read 📚:- https://t.me/Think_CreativeHub
$5.4M Funding for Tenor
Tenor has raised $5.40 million on December 19, 2024. This platform enables managers to rehearse difficult conversations with realistic voice AI characters and receive instant feedback for improvement.
#Funding#AI#VoiceAI#Management#Feedback#Conversations#Tech#Startup#Investment#Training#Innovation#Leadership#Simulation#Dialogue#PersonalDevelopment#Business#Growth#Application#Software#Tenor