Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🛜🔠🔠🔠🔠🔠
🔠🔠🔠🔠
💛 Alkimyogar
Bu kitobni qancha kop maqtasam arziydi! Qayta qayta tinglang Va o'qing!
Va albatta barcha ORZU maqsadlaringiz Amalga oshganda bizni ham albatta tabassum bilan eslab qo'ying
🤍
🤍 SİZ SO'RAGAN AUDİO KİTOB!
#audiobook
💛@Biglibrary_uz
🔠🔠🔠🔠🔠🔠🔠🔠
🎙 Ichindagi ichindadur
💡 Hayrlı kun kitobsevar qadrdonlarim!! Sizga Juda zo'r
#audiobook🎧 bilan keldim.
Albatta tinglang! Juda ham zo'r kitob! Qancha tariflasam , shuncha so'zlar ojizlik qiladi! Ming marta maqtagandan ko'ra bir marta o'zingiz mazasini tatib koring 🫂
Bu kitobni o'qiganlar Yoki tinglaganlar bormi ,
🔥 reaksiyalarni bosib qoying
@Milliarderlarim
#Narratorr#Audiobook#amp#TTS
Join the Narratorr - Audiobook & TTS beta on ✈️#TestFlight
🔗 Link: https://testflight.apple.com/join/Fv19nvDd
Shared by Dimitri
📖Title : The Frozen River
✍️Author : Ariel Lawhon
⭐️Rating : 4.38/5 (Goodreads)
📆Published : Dec 05, 2023
————————————————
Summary:The Frozen River by Ariel Lawhon is a historical mystery set in 1789 Maine. Midwife and healer Martha Ballard is called to examine the body of a man found trapped in the frozen Kennebec River. While authorities quickly declare the death an accident, Martha suspects something far darker. As she records events in her diary and follows the clues, she uncovers a web of violence, secrets, and injustice involving powerful members of the community. Determined to seek the truth despite threats and social pressures, Martha risks her reputation and safety while fighting for justice in a society where women’s voices are often ignored.
————————————————
#fiction#mystery#audiobook#historical#thriller#ariellawhon#thefrozenriver@Bookslibraryofficial
📖Title : More Days at the Morisaki Bookshop
✍️Author : Satoshi Yagisawa
⭐️Rating : 3.85/5 (Goodreads)
📆Published : Dec 06, 2011
————————————————
Summary:More Days at the Morisaki Bookshop follows Takako as she continues healing while living above her uncle’s secondhand bookshop in Tokyo’s Jimbocho district. Surrounded by books and familiar faces, she confronts lingering grief, evolving relationships, and quiet uncertainties about the future. The novel focuses on small, meaningful moments, showing how literature, routine, and human connection gently restore a sense of belonging. Through everyday interactions, it portrays healing as gradual, imperfect, and deeply tied to community, memory, and the comforting presence of books.
————————————————
#fiction#japan#cozy#audiobook#romance#moredaysatthemorisakibookshop#satoshiyagisawa@Bookslibraryofficial@free_novellas@eternalmantra
📖Title : Bemused
✍️Author : Farrah Rochon
⭐️Rating : 3.92/5 (Goodreads)
📆Published : Jan 07, 2025
————————————————
Summary:Five sheltered sisters living in a quiet seaside village learn that they are the legendary Muses, daughters of Mnemosyne, Goddess of Memory. After their mother is kidnapped by Hades, the sisters are forced to leave their protected lives behind. Guided by Calliope’s leadership, they journey through dangerous lands, face mythical trials, and uncover their divine powers. Along the way, they confront fear, doubt, and destiny itself. Through music, storytelling, courage, and unity, the sisters strengthen their bond and transform from overlooked performers into heroic figures, embracing their true identities and shaping their own legendary “gospel truth.”
————————————————
#fantasy#mythology#retellings#fiction#historicalfiction#audiobook#bemused#farrahrochen@Bookslibraryofficial@free_novellas@eternalmantra