Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🚀 Great Start of SLEX Launchpad!🎉
⚡️The first day of SLEX Launchpad sales was a huge success with over 37,78% of allocations sold out! Whitelist participants, you have a last chance to be part of this exclusive event, but hurry up as allocation actively decreases with high users demand📈
🗓️The sale ends tomorrow, February 17th. Don't miss the last chance to take exclusive advantages of SLEX Launchpad.
#SLEXLaunchpad#LastChance#CryptoSale
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🎉Amazing Success of the first SLEX Launchpad! 🚀
📈A huge thanks to all participants who joined the first SLEX Launchpad! Your participation made it an outstanding success!
🔥
🤝Don't miss out on future opportunities - follow us on our social channels. Here's you can find more interesting updates and events soon:
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
#SLEXLaunchpad#SLEX#SLEXSale#StayTuned
🚀The Time Is UP: Today is the First Day of SLEX Launchpad Sale! ☄️
⚡️The wait is over! The first SLEX Launchpad officially starts today, February 15th at 12:00 UTC, after our Whitelist successfully closed with over 4000 participants. This marks the beginning of exceptional earning opportunities for our community🎉
🔥Premier Project Access: SLEX token holders, get ready for exclusive access to Tier-1 crypto projects. These handpicked projects offer a rare chance to invest in potentially profitable tokens.
💰Maximize Your Earnings: participate in the Launchpad to unlock staking rewards and additional trading benefits on SLEX Exchange.
📅 Important Reminder for Whitelist Members:
👀Due to the fact that token allocation and the time of the sale are limited, we recommend to deposit funds on your account in advance.
✍🏻If you did not create an account on SLEX yet, make sure that you create one under the email you specified in the Whitelist application form to be able to participate in token sale.
#SLEX#LaunchpadLive#SLEXTokens#SLEXLaunchpad#SLEXWhitelist
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🚀Let the Sale Begin: The first SLEX Launchpad for 4000 Participants Starts on February 15th! 🎉
⚡️We are thrilled to announce that the Whitelist on SLEX has been successfully closed with more than 4000 participants. And now we are at the finish line because it's only two days until the launch of the much-anticipated SLEX Launchpad!⚡️
📈Mark your calendars and prepare to join SLEX Launchpad to get access to exceptional ways of earning:
🔥Access to Tier-1 Projects: SLEX token holders will gain exclusive access to Tier-1 projects, offering a gateway to the most promising and innovative crypto projects.
💰Staking Rewards and Trading Benefits: Token holders can get rewards from staking and additional trading bonuses at SLEX Exchange.
📅 If you are a Whitelist member check out email for more details and instructions about participation in the first SLEX Launchpad!
#SLEX#LaunchpadAnnouncement#CryptoInnovation#SLEXTokens#TradingBenefits#SLEXLaunchpad#SLEXWhitelist
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🚨 Last Chance: SLEX Whitelist is Coming to an End! ⏳
🔥Time is ticking! The exclusive opportunity to join the SLEX Whitelist only for the community is nearing its end on February 1st. This is an exceptional way to get early access to a limited allocation of SLEX Coins before Public listing!
🤝Take your last chance and join SLEX Whitelist: slex.io/launchpad/slex
🤔We've also got an exciting way to show you the ambitious and in-depth look at SLEX plans and vision on Binance:www.binance.com/en-AE/feed/post/1058789
#SLEXWhitelist#SLEXExchange#JoinNow#BinanceArticle#SLEXCoin#PublicSale#SLEXLaunchpad
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter