Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🎇Happy #TP6Anni!!
💙Join our 6th Anniversary Celebration and win OVER $10,000 Rewards!
Dive into👇
https://app.galxe.com/quest/TokenPocket/GCwbMtTHJW
💪We would like to express our gratitude to all TP users and partners, and we hope to work together with you in the future to create a new era of blockchain!
❤️Thank BitlayerLabs, MerlinSwap, cyclenetwork_GO, and TNA_Protocol for supporting the 1st round of the #TP6Anni celebration! Stay tuned for more!
💙Thanks to all the #TPFam who participated in the #TP6Anni celebration!
🏆Check if you are on the #TP6Anni Giveaway Winner List!
1️⃣ 50 BitlayerLabs Lucky Helmet NFT
👉https://docs.google.com/spreadsheets/d/1qjIkzt1_CM_LfNaoy4vVIrqSmB5hF4oAN5pIScYgeQM/edit#gid=0
2️⃣ $2,000 esMP token Giveaway
👉https://docs.google.com/spreadsheets/d/1tt_AiQmQYZk3EFS-6hEwTZFBI0iTcJDK6YD110TZeQU/edit#gid=0
3️⃣1,000 Piggy Boxes V3 Giveaway
👉https://docs.google.com/spreadsheets/d/1_Aj9cgq0SdyJHQjztl-TWGwHQb_NHgWIbaonwzSH7vA/edit#gid=0
4️⃣$3,000 $TNA and 50 Tapnames Whitelists Giveaway
👉https://docs.google.com/spreadsheets/d/1ZiCOS_nQ897Vj5p5TgoMi607hCCk2IILhwVn6-w-MjE/edit#gid=0
💙Thanks for your participation! If you have any questions, please join https://t.me/tokenPocket_en.
🎇Happy #TP6Anni!!
💙Join and win 50 BitlayerLabs Lucky Helmet NFT Whitelists Giveaway on Galxe!
👉https://app.galxe.com/quest/TokenPocket/GCddyth8TC
🟧Bitlayer Lucky Helmet is the official NFT launched by BitlayerLabs, a symbol of identity representing the contributions of builders in the Bitlayer community.
#TP6Anni#TokenPocket#Bitlayer
🎇Happy #TP6Anni!!
💙Join and win $2000 esMP Tokens Giveaway on Galxe!
👉https://galxe.com/TokenPocket/campaign/GCyyEths19
🟧MerlinSwap stands as the 1# Decentralized Exchange in the #Bitcoin ecosystem, aimed to become the liquidity hub for BTC and Bitcoin eco-assets, including #BRC20, #BRC420 and native tokens across MerlinLayer2 Bitcoin layer2.