Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#Impeachment: con 221 favorevoli e 212 contrari, la Camera dei Rappresentanti formalizza l'inchiesta di impeachment nei confronti di Joe Biden.
Questo darà alle Commissioni della Camera un maggior potere ispettivo nei confronti della Casa Bianca e saranno in grado di ottenere testimonianze e prove.
📢 EXCLUSIVE: House Dems secretly meet with GOP to kill Biden impeachment. Republicans consider Biden's record of cooperation. Fact sheets shared to quash inquiry. Dems defend Biden's firing of Ukrainian prosecutor. FBI probe alleges bribery scheme. Biden received funds from brother. GOP demands White House docs. Biden communicated with son via email alias. Impeachment inquiry framework to be formalized. Corruption investigation continues. Stay tuned for updates! 🕵️♀️🔍#Politics#Corruption#Impeachment
https://www.foxnews.com/politics/house-oversight-democrat-quietly-meeting-gop-lawmakers-effort-quash-impeachment-inquiry-sources
Subscribe to @BadVolfNews
⚖️🇺🇸HOUSE DEMOCRATS LAUNCH IMPEACHMENT AGAINST DEFENSE SECRETARY HEGSETH
🔹 Six articles filed by Rep. Yassamin Ansari over unauthorized Iran military strikes without Congress approval 📋
🔹 Accusations include targeting civilians, destroying girls school in Minab, Iran during operations 🎯
🔹 Illegal double-tap strikes on Caribbean drug boats — hitting first responders after initial attack 🚢
🔹 Signalgate scandal: sharing classified Yemen strike details via Signal app to unauthorized personnel 📱
White House dismisses as political theater, but war crimes allegations stack up! 🔥
#USNews#impeachment#Hegseth
@america
On January 26, 1998, President Bill Clinton held a news conference and denied having sexual relations with Monica Lewinsky, a 22-year-old White House aide. Later that year, he was impeached for lying about the affair but was acquitted by the Senate and finished his term.
🇺🇲🧐
[Read more]
@googlefactss
#Clinton#Lewinsky#Impeachment#USHistory#FactCheck#ItWasntMe
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
Argentina Investigates LIBRA Token Misconduct
Argentina's President Javier Milei calls for an investigation into LIBRA token's rug pull, requesting the Anti-Corruption Office's involvement to assess potential misconduct by government members. Findings will be forwarded to the court. Opposition considers impeachment due to the incident. Links: Statement, Watch, Details.
#LIBRA#Crypto#Argentina#investigation#rugpull#president#JavierMilei#impeachment#KIPProtocol#AntiCorruption#fundflow#temporalanalysis#MELANIA#ENRON#Solana#ETF#Bitcoin#adoption#blockchain#corruption#misconduct