Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#соцсети#игра#hamstercombat
🟠Знаете про тренд с 🐹«тапать хомяка»?
‼️В мае 2024 года в соцсетях завирусилась игра Hamster Kombat, суть которой заключается в том, чтобы нажимать (тапать) на хомяка и зарабатывать монетки.
❓Hamster Kombat— это приложение внутри мессенджера Telegram, которое представляет собой модель
📈криптобиржи. Пользователь играет за генерального директора биржи. Чтобы заработать деньги, ему нужно нажимать (тапать) на пузико маскота игры — хомяка-трейдера. Чем больше тапов, тем больше заработанных монет.
4️⃣Монеты также можно зарабатывать, приглашая друзей в приложение.
🟠На данный момент официальный канал игры насчитывает более 35 миллионов подписчиков.
🟠Игра интересна пользователям не столько из-за хомяка, сколько за «возможность заработать реальные деньги в будущем».
Как утверждают создатели, заработанные в игре монетки могут превратиться в реальные деньги после листинга (процедуры вывода криптовалюты на биржу). Вывести ее обещают на блокчейн TON, созданный командой Telegram.
☯️Нам метод «заработка» с помощью нажатий на хомяка кажется совсем неубедительным. Но время покажет. Пока именно временной ресурс самое ценное, что 🐹 хомяк отнимает у миллионов людей.
Будь в теме с 🍀
🎧⤴
🐹Tapped for Months, Earned Pennies: Hamster Combat's Epic Letdown😁
After months of relentless tapping, eager "hamsters" finally witnessed the listing of Hamster Combat. These devoted tappers dreamed of millions and luxurious yachts, but reality hit hard when the coin's value failed to meet expectations. Instead of fortune, participants are left with a mere $15 — or even less — in their pockets. This ironic twist highlights the pitfalls of hoping to get rich simply by tapping a phone screen.
Chorus:
Tapped the screen, chased the dream so far,
But all we got was a fading star.
Promises of millions turned to dust,
Hamster wheels that lost our trust.
Verse 1:
Half a year we tapped away,
Fingers numb every single day.
Hamster Combat was the name,
Thought we'd rise to wealth and fame.
Dreams of yachts and cash in hand,
Building castles made of sand.
Listing day, the curtain's drawn,
Fifteen bucks and illusions gone.
Chorus:
Tapped the screen, chased the dream so far,
But all we got was a fading star.
Promises of millions turned to dust,
Hamster wheels that lost our trust.
Verse 2:
Believed the hype, we took the ride,
Blinded by that crypto tide.
Tapping screens like it was gold,
Never thought the truth be told.
Hamster races led nowhere,
Woke up from that millionaire's dare.
Pocket change is all we found,
Feet now firmly on the ground.
Chorus:
Tapped the screen, chased the dream so far,
But all we got was a fading star.
Promises of millions turned to dust,
Hamster wheels that lost our trust.
Verse 3:
Lessons learned, the hard school's best,
There's no shortcut to the crest.
Tap and hope won't pay the bills,
Real work earns the real thrills.
Chasing coins in cyberspace,
Never again will we embrace.
Time to step off hamster tracks,
Focus on the real facts.
Chorus:
Tapped the screen, chased the dream so far,
But all we got was a fading star.
Promises of millions turned to dust,
Hamster wheels that lost our trust.
Bridge:
We woke up from that digital trance,
No more betting on a chance.
Hamster Combat wrote the end,
Now it's time our ways to mend.
#CryptoReality#HamsterCombat#CryptoLessons
#TONCryptoNewsRapStyle
🎧@toncoin_rap
🌺Did you know that BOSSES have appeared in BLUM? I'm shocked too😊
💣Easy busy- With us, you'll be the first to know about the best airdrops, giveaways, and projects.
#blum#taptoearn#not#notcoin#hamster#hamstercombat#gametoearn#bitcoin#ShowUsHowUBlum
What do you think about this?👍