Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Upcoming Airdrops Alert! 🚀
Hey everyone! 🎉 If you missed out on the Dogs airdrop, don’t worry! There are some exciting new airdrops coming up that you won’t want to miss. Check out these potential big earners:
1. Major🌟
1. X Empire 🏰
3. Cats🐈
4. Memefi🎭
-Confirmed Listing Date: October 9th
-All WILL BE LISTED IN ABOUT A MONTH TIME , SO JOIN AND GET FREE TOKENS BEFORE ITS TOO LATE!!!
#Airdrops
🎁 The #giveaway with 4EVERLAND has officially ended! A big thank you to #TokenPocket for their support and to all participants.
👇🏻Keep an eye out for upcoming thrilling #airdrops and don't forget to claim your $4EVER points at: https://dashboard.4everland.org/quest/tp
🥳We are thrilled to announce that UXLINK has made strategic partnership with @LumozOrg
to build Social Growth Layer(SGL) together!
Our ecosystem fund @UFLY_Labs
will invest @LumozOrg and we will empower Lumoz social growth & business development globally especially in Japan and Korea market & community.
💰Lumoz native token $MOZ will be #TGE on CEXs soon and we will make ONE MILLION dollar value #Airdrops to qualified $UXLINK holders and stakers!
Lumoz is the leading Modular Compute Layer for ZK & AI. Lumoz uses PoW mining mechanism to provide computing power for Rollup, ZK-ML and ZKP verification.
Please stay tuned for our updates!❤️
Channel: Legit Airdrop ️
Members: ~142.24K
💢 Username: @legit365airdropss
Description:
Welcome dear subscribers! We will do our best to share the legit airdrop campaigns timely. If You Need Any Airdrop Project Promotion Then Contract here @Legit365airdrop1 Buy ads: https://telega.io/c/legit365airdropss
🏷 Tags: #airdrop
#airdrops#cryptocurrency
https://telegramchannels.me/channels/legit365airdropss
$ORB and $MOZ #Airdrops done just now, #UXLINKseason2 stakers please kindly check your wallet address to get the token❤️https://arbiscan.io/address/0x0698e377ca9dbfb5c77503d611c6f1f38cf46ba2
#Airdrops Are Making Millionaires In Crypto – Here’s How [Full Guide Cosmos, LUNA & More]
#cryptogemtokenshttps://cryptogemtokens.com/airdrops-are-making-millionaires-in-crypto-heres-how-full-guide-cosmos-luna-more/
Phantom Wallet Dismisses Token Rumors
Phantom Wallet team clarifies: no plans for a native token or airdrop. Focus remains on improving the token and app discovery mechanism. More details: Read here
#Phantom#airdrops#wallets#Crypto#VC