Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Jake Paul knocked out Mike Perry in the 6th round 👊
I expected to win. I should have won in the first round, but Perry survived. Mike Tyson, you're next, sign the contract.
#Box
👁Subscribe to Main Event | Sport News
Jake Paul on the fight with Mike Perry:
"Maybe at the beginning, he’ll land a couple of heavy shots, maybe he’ll be all wild and unpredictable, but as the fight progresses, I’ll start breaking him down with my footwork, jab, and body shots."
#Box
👁Subscribe to Main Event | Sport News
Diaz Sues Organizers of Fight with Masvidal
#box#mma
Nate Diaz has filed a lawsuit against the organizers of the fight with Jorge Masvidal.
Nate claims he had an agreement for a $10,000,000 payout for the fight. He received an advance payment of $1,000,000, with the remaining $9,000,000 to be paid after the fight. The lawsuit states that the company is refusing to make the payments, claiming that the event was unprofitable.
👁Subscribe to Main Event | Sport News