Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🐹Solution for the mini-game
in Hamster Kombaton September21!
💎Receive a diamond for completing the task!
🔔Subscribe👉Join Hamster
⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
#crypto#hamster#key#code
#hamsterkombat#chiper#taptap
🐹Hamster Kombat:Daily Combo for August30th!
🔸 Cointelegraph
🔸 Risk management team
🔸 Setting up business processes
Combine these cards to win 5,000,000 coins! 💰
🔔Subscribe👉Join Hamster
⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
#crypto#hamster#key#code
#hamsterkombat#chiper#taptap
🐹Hamster Kombat:New Card Alert!
📝Your Human Talent
💡 Is your most important talent.
📊Profit per hour: +1.5K
💰Cost: 35,000 coins
🔔Subscribe👉Join Hamster
⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
#crypto#hamster#key#code
#hamsterkombat#chiper#taptap
🐹Hamster Kombat:New Card Alert!
🔍 No Expensive Mistakes
If you don’t manufacture a quality product, all you’ve got at the end is a bunch of expensive mistakes.
💰 Profit per hour: +800
💸 Cost: 17,000 coins
🔔Subscribe👉Join Hamster
⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
#crypto#hamster#key#code
#hamsterkombat#chiper#taptap
🐹Hamster Kombat :New Card Alert for August 28th!
🗣️ Speak Clearly, If You Speak at All
“The way to get started is to quit talking and begin doing.”
Profit per hour: +400
Cost: 10,000 coins
🔔🔔Subscribe👉Join Hamster
⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
#crypto#hamster#key#code
#hamsterkombat#chiper#taptap
🐹Solution for the mini-game with a key inHamster Kombaton August 27th! 🔑
➕A new mini-game has been added!
Now, connect hexagon tiles of the same color to earn coins.
⭐️Play as many times as you want!
🔔Subscribe👉Join Hamster
⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
#crypto#hamster#key#code
#hamsterkombat#chiper#taptap
🐹Hamster Kombat :New Card Alert for August27th!
🌾 Feed a Growing Population & Enhance Food Security
In the next 30 years, we will need to produce as much food as was produced in the last 10,000 years.
Profit per hour: +4K
Cost: 60,000 coins
🔔🔔Subscribe👉Join Hamster
⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
#crypto#hamster#key#code
#hamsterkombat#chiper#taptap
🐹Solution for the newmini-game
in Hamster Kombaton August 26th!
🔔Subscribe👉Join Hamster
⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
#crypto#hamster#key#code
#hamsterkombat#chiper#taptap
🐹Hamster Kombat:New Card Added!
🌕MoonPay is now available!
A whole world of crypto in one simple account. Buy, sell, and swap seamlessly. Say hello to the new way to crypto!
💰Earn 20K per hour with this card.
🔔Subscribe👉Join Hamster
⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
#crypto#hamster#key#code
#hamsterkombat#chiper#taptap