Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🪙YouTube Tasks
Complete and earn 🪙 in Major!
▶️Watch Video #1
Reward: +5,000 ⭐️
Code: 070624
▶️Watch Shorts #4
Reward: +1,500 ⭐️
Code: 159390
🪙 Enter the codes and collect your stars now!
🔔Subscribe
➡️Join Major
➖➖➖➖➖➖➖➖➖➖
#major#crypto#taptap
🪙Major:New Combo of the Day October 18!
➡️Number sequence: 2:12:4:10
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 14!
➡️Number sequence: 6:3:4:5
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 12!
➡️Number sequence: 10:14:12:1
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe 👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 11!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 10!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 9!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 8!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day October 7!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day September 23!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day September 22!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap
🪙Major:New Combo of the Day September 19!
💱 Complete the new combo to earn +5000🪙 points for your rating!
🔔Subscribe👉Join Major
➖➖➖➖➖➖➖➖➖➖
#major#combo#taptap