Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🔥NEW RELEASE🔥
😁Crucifix Masterclass by Brian Glick😁
➡️A direct student of legendary coach John Danaher, Brian breaks down the crucifix in a methodical, accessible system designed to transform this powerful position into a high-percentage part of your game.
➡️Instead, it leverages advanced, submission-based control points that create tremendous vulnerability in your opponent while giving you near-total dominance.
̶$̶1̶9̶7̶😍$14.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#BrianGlick#Submission#NoGi#NewWave
💁♀️Buy
💁♀️
😁Submission Mastery: Omoplata by Giancarlo Bodoni😁
➡️Giancarlo Bodoni — 2x ADCC champion, CJI standout, and elite New Wave athlete under the legendary John Danaher and Gordon Ryan — unveils his groundbreaking system for mastering one of grappling’s most underutilized weapons: the omoplata.
➡️This is not just a submission tutorial. This is a total redefinition of the omoplata for the modern no-gi game — built on elite-level mechanics, control, and finishing options that go far beyond what you thought possible.
$197😍$14.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#GiancarloBodoni#Submission#NoGi#NewWave
💁♀️Buy
💁♀️
🔥NEW RELEASE🔥
😁Loop Choke by Nicholas Meregali😁
➡️The Loop Choke is one of the most powerful and underrated submissions in Jiu-Jitsu.
➡️In this complete 2.5-hour series, Nicholas breaks down every layer of the position, from the core mechanics to advanced scenarios, covering how to attack from bottom. and top
$127😍$14.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#NicholasMeregali#Submission#Gi#NewWave
💁♀️Buy
💁♀️
🔥DEAL OF THE WEEK🔥
😁Systematically Attacking The Arm Bar by Gordon Ryan😁
➡️DEAL ENDS ON APRIL 7TH
$349😍$9.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#GordonRyan#ADCC#Submission#FloGrappling
💁♀️Buy
💁♀️