Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🔥Airdrop - Bluefin x OKX Cryptopedia ✅
💰Total Reward: $605,000+ worth of tokens — including $550K in BLUE + $55K in SUI — up for grabs through Cryptopedia Season 38
☀️Airdrop Link :- Click Here
⚙️How to Participate?
♦️Connect your OKX Wallet (SUI Network)
♦️Complete all tasks within the Bluefin campaign on Cryptopedia
♦️Verify your actions to be eligible
♦️Tasks are simple and interactive — don’t miss out
🎁Eligible participants will earn a share of 605,000 USDT in token rewards
📆Campaign Ends: 6 September 2025 – 7:00 AM UTC
📌Explore DApps, complete missions, and earn rewards this is Web3 made fun and rewarding
🔗 Source: https://x.com/wallet/status/1943597905996034069
®Note - Please do your own research (DYOR) before joining to any airdrops project, also airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens required
#OKX#Bluefin#Cryptopedia#Airdropcomic#Web3Rewards
📰 CRYPTO NEWS
🆕️The founder and CEO of #CryptoQuant stated that compared to the previous cyclical peak, the fundamental elements of the bitcoin network can maintain a market value three times higher than the current one. He considers it "possible" to "keep" the bitcoin price at $265,000.
🆕️As part of the presale, #WATER raised $41 million. Which also makes WATER the largest Memecoin pre-sale to date, with over 26,000 wallets participating. The team has regained control of its account in X.
🆕️50 Cent's #Twitter account was hacked in order to promote the Solana Meme Coin.
🆕️Internet Computer will launch the #ICP Hub Accelerator Program 2024, which aims to help early blockchain projects transform their concepts into market solutions, create a strong blockchain innovation ecosystem and promote technological progress in the ICP community.
🔹 21 million #LINKS ($295 million) of non-convertible Chainlink contracts have been unblocked today.
🆕️DAO Osmosis supports a commission-free bridge for transferring bitcoin to the #Cosmos ecosystem.
🆕️Scroll ZKP presents "Scroll Sessions", a loyalty program to reward the Scroll Marks community for their participation and involvement in the #Scroll ecosystem.
🆕️Arbitrum introduces the "Layer Leap", a single-stage bridge from L1 to L3 for the #Orbit ecosystem.
🆕️#Reef plans to launch a new product on June 26.
‼️ Dogwifhat Whales dropped #WIF by 16 million in a week.
🆕️#Fantom has released #Sonic's third management offering, which includes an annual token destruction mechanism, as well as the launch of Sonic Spark and Sonic University.
🆕️#Bluefin announces integration with Wormhole Connect. The Wormhole community will participate in the future release of Bluefin tokens.
🆕️#StacksNakamoto has announced the completion of 90% of the work on the project and is preparing for the official launch on July 15. The Nakamoto Stacks update should increase the transaction speed to 5-10 seconds, which is about 100 times faster than the current speed. ➡️ This is a significant event for the Stacks project and the Bitcoin ecosystem, will improve the speed, overall efficiency and scalability of Layer2 on #Bitcoin, promising faster and more efficient transactions for users.