Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
😄Draw
➖➖➖➖➖➖
🔘 Drawis commonly used as a verb that means creating a picture or image
🔜My cousin drew our family using different coloured pencils.
🔜My daughter has just learned to draw!
🔘We can also use the verb ‘draw’ to mean attracting attention - someone wanting to look at something.
🔜The amazing singer drew a huge audience.
🔜A World Cup game is guaranteed to draw a large number of viewers!
🔘 Drawas a noun can also describe competition results that are equal.
🔜The football match ended in a draw – it was 1:1.
🔜This boxer has never lost a fight - he has six wins and a draw.
#Draw👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys
⚠️ The project was suspended. Funds may be at risk.
🌟Starverse — Telegram Stars Farming and Everyday Giveaways
Earning stars has never been so exciting! #Starverse is a game where your tickets turn into real money. A project from the TgLab team, creators of the popular TON Dating mini app.
⏳Farming
Every hour you can turn on farming and take a part of the total income of the players.
Half of all revenue goes to farmers — the more tickets you have, the bigger the drop.
Farm, reinvest and invite friends — you'll get 15% of their purchases.
💰Golden Ticket
Every day at 9:00 UTC a winner is randomly selected and receives 15% of all purchases made during the day.
How to participate:
- farm at least 3 hours a day
- buy at least one ticket on the day of the drawing
💰Easy Withdraw
Got Stars? You can immediately transfer them to your Telegram account or convert to $USDT without delays.
⭐️Start farming now!
#stars#farming#draw#web3