Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
📉Крах токена LIBRA стал самой обсуждаемой темой
🚩 Президент Аргентины Хавьер Милей оказался в центре скандала после обрушения токена LIBRA. Цена взлетела до $5, но затем рухнула ниже $1. Пострадали 40 000 инвесторов, а ущерб превысил $4 млрд.
💻 В соцсетях обсуждают роль Милея в афере и требуют его отставки. Также под удар попал Хейден Дэвис, создатель LIBRA и Melania, которого обвиняют в финансовых махинациях.
🚩 Многие юзеры призывают отказаться от мемкоинов на Solana, так как мошенники используют этот блокчейн для запуска фейковых проектов.
🚩 Solana занял второе место по числу упоминаний в соцсетях. Юзеры сходятся во мнении, что курс SOL напрямую зависит от обстановки вокруг мемкоинов, развернутых на этом блокчейне.
🚩 Пользователи также поддержали предложение Илона Маска по проверке золотых резервов Форт-Нокса.
#LIBRA#Solana#Криптовалюты
Token LIBRA Crashes 94% in Hours
🚨 Argentine President Javier Milei's promoted token LIBRA plummeted 94% shortly after launch, with insiders cashing out over $107 million. Initial market cap peaked at $4.56 billion but has dropped to $174 million. The token was marketed as a tool to boost Argentina's economy. Milei later removed his promotional post and blamed political opponents for the fallout.
📉 Link to details: Full story
#Crypto#Argentina#LIBRA#Trading#MarketCrash#TokenSale#InsiderTrading#ETH#VC
#Crypto#Argentina#LIBRA#Trading#MarketCrash#TokenSale#InsiderTrading#ETH#VC
Market Moves: KIP Protocol & Canada Banks
KIP Protocol states token issuance is under Kelsier Ventures. Argentine President Milei pledged support but will reinvest $100M into Libra tokens. Meanwhile, Canada's National Bank and Bank of Montreal acquire a total of $1.315B in $MSTR shares. KIP Protocol Link
#KIP#Kelsier#Argentina#Libra#Bitcoin#MSTR#Canada#Finance#Investment#MarketMaking#Crypto#VC
💰Libra: Facebook confirms its cryptocurrency launching in 2020
#Libra is designed not to be a speculative asset, like #Bitcoin, but a form of digital money backed by a reserve of assets.
The company has formed the nonprofit Libra Association with 27 other partners to oversee Libra and its development. The partnership includes venture capital firms, nonprofit organizations, #cryptocurrency firms, and massive corporate financial, telecommunications, and technology service providers, including #Coinbase, #Mastercard, #Visa, #eBay, #PayPal, #Stripe, #Spotify, #Uber, #Lyft, and #Vodafone.
While the Libra Association will have members based globally, it will be headquartered in Geneva, Switzerland🇨🇭
Facebook has a business incentive to build on top of the Libra #blockchain, and it’s launching its own subsidiary to do just that called #Calibra (see the GIF below - Credit: Facebook). According to Kevin Weil, Facebook's VP of Product, Calibra will live inside of Facebook Messenger and WhatsApp at launch, but will also have a standalone iOS and Android app.
🔗 Read more the Verge.
🚀@PerspectiveIX
La manera de hacer enojar a cada signo😤:
#Aries♈️: Ignorandolo.
#Tauro♉️: Pedirle más de lo que puede hacer.
#Geminis♊️: Presionarlo a hacer algo que no quiere hacer.
#Cancer♋️: Obligale a admitir que está equivocado.
#Leo♌️: Niego sus palabras.
#Virgo♍️: Que le lleven la contraria en lo que sea.
#Libra♎️: Excluyendole de tus planes.
#Escorpio♏️: Cometiendo errores absurdos.
#Sagitario♐️: Cancelando un plan a última hora.
#Capricornio♑️: Dile cómo tiene que hacer las cosas.
#Acuario♒️: Cortale las alas.
#Piscis♓️: No le des las gracias nunca.
@EsTuHoroscopo.🔮
Lo que a los signos mas les gusta de su pareja🥰:
#Aries♈️: Que le dejé ponerse sus sudaderas.
#Tauro♉️: Que le haga una playlist.
#Geminis♊️: Que le dejé hablar de sus pasiones.
#Cancer♋️: Que hable de sus sentimientos sin timidez.
#Leo♌️: Que le diga que es el/la más guapx.
#Virgo♍️: Que siga hablándole aunque desaparezca durante días.
#Libra♎️: Que tengan el mismo gusto musical que él/ella.
#Escorpio♏️: Que se pueda hablar de cualquier cosa con su pareja.
#Sagitario♐️: Que se ría de cualquier meme que le enseñe.
#Capricornio♑️: Que vea cualquier serie con él/ella.
#Acuario♒️: Que entienda que necesita su espacio.
#Piscis♓️: Que recuerde cualquier pequeño detalle.
@EsTuHoroscopo.🔮
Milei Withdraws LIBRA Support Amid Cash Out
Argentinian President Javier Milei retracts his endorsement of $LIBRA after insiders reportedly cashed out $107 million. The move raises questions about transparency and the impact on the cryptocurrency's reputation. For more details, visit The Block.
#Argentina#Milei#LIBRA#Crypto#DeFi#Blockchain#Investment#Transparency#Finance#Market#News#Updates#Economy#InsiderTrading#Regulation#Securities#Volatility#Trends#DigitalCurrency#Cryptocurrency
Insights on Crypto Developments
🚨 Important updates in the crypto sector:
1. Trump's Crypto Czar, David Sacks, hints at "important announcements" for digital assets soon.
2. KIP Protocol claims support for the LIBRA token by Argentina's president. Backed by Animoca Ventures and involved with the AI project *Open Campus*. Read more
3. Argentine President Mile clarifies his earlier tweet supporting a private startup, stating he lacked details at the time and has since deleted the post after further understanding. Read more
#Crypto#AI#VC#Animoca#Argentina#KIPProtocol#Trump#DigitalAssets#Milei#LIBRA#OpenCampus#Startup#Partnerships#Decentralization#Finance#Blockchain#Tech
Investors Flock to Legal Tech Startups
Despite a downturn in the venture capital market, record investments were made last year in legal tech startups focusing on AI solutions. These startups are securing rounds of $50-100 million as investor interest surges. Read more here: FastFounder article
In other news, President Javier Milei of Argentina clarified that he only disseminated information about the LIBRA token, not promoted it, and confirmed meetings with individuals involved in its launch. This comes after a brief spike in LIBRA's price following his shared purchase instructions. Additionally, the CEO of Jupiter, Ben Chow, has resigned amid a rising scrutiny of the LIBRA project. Full News
#AI#Crypto#VC#LegalTech#StartupInvestment#Argentina#LIBRA#VentureCapital#Investment#Technology#M&A #Blockchain#XRP#SEC#Audit#Innovation#TechTrends#MarketTrends
AI Infrastructure Opportunities Emerging!
New potential for large-scale AI infrastructure projects! 🤖🔗 While fears of AI replacing humans persist, the reality shows a need for collaboration. Specialized platforms are essential for this interaction. Check out inspirations for creating your own platform here.
Additionally, Nansen analysts report that 15,431 wallets experienced significant profit/loss on LIBRA: 86% lost $251M, while a few gained $180M.
Recent crypto updates: BTC ETF outflow: $64M, ETH ETF inflow: $19M. During the last 24 hours, 74K traders were liquidated, totaling $139M. Largest liquidation: ETH/USDT at $2M on Binance.
#AI#Crypto#VC#Blockchain#Investment#Finance#Tech#DataScience#MarketTrends#Nansen#Wallets#LIBRA#BTC#ETH#Liquidation#ETFs#ProfitLoss#Infrastructure#Innovation#DigitalEconomy#Trading
Argentina's Opposition Eyes Impeachment Over LIBRA
Argentina's opposition is considering impeachment for President Milei after conflicting support for the LIBRA token. This follows a controversial launch that saw rapid investment and then a significant drop in value, leading to accusations of mismanagement and deception. The situation raises questions about political influence in cryptocurrency projects.
Read more: Reuters
#Argentina#LIBRA#Crypto#Impeachment#Milei#Investment#MarketManipulation#EconomicCrisis#Blockchain#DeFi#RugPull#Politics#Cryptocurrency#TokenLaunch#InsiderTrading#Securities#AI#VC