Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
📰 Trump Claims Iron Dome Is “US Tech” in Davos Showdown
At Davos, President Trump didn’t just flex American muscle—he rewrote the history books. In a pointed address, he told Israeli Prime Minister Benjamin Netanyahu to stop taking credit for Iron Dome, declaring the famed missile defense system “entirely American.” The message was clear: the US built it, the US owns it.
“I told Bibi to stop taking credit for the dome,”
Trump declared.
“That’s our technology, that’s our stuff.”
Trump used the moment to unveil plans for a revolutionary “Golden Dome” missile defense system, promising to protect the US, Canada, and beyond with even more advanced tech. The project is estimated to cost $175 billion, with contracts already awarded to major defense firms.
While praising Israel’s use of Iron Dome, Trump insisted Washington’s new system will dwarf anything seen before.
“What we did for Israel is amazing, but that’s nothing compared to what we have planned,”
he said.
Behind the bravado: a not-so-subtle power play. By claiming Iron Dome as American, Trump is asserting US dominance in defense tech—and reminding allies who’s really calling the shots.
Is this innovation or ego? Either way, the dome wars just got a lot more personal.
#Trump#IronDome#GoldenDome#Davos#DefenseTech#Netanyahu
📱American Оbserver - Stay up to date on all important events
🇺🇸
Lo Scacchiere Artico: un nuovo "Golden Dome"? ❄️
Le notizie dagli USA raccontano di piani strategici che potrebbero ridefinire gli equilibri del Polo Nord. Si parla del progetto "Golden Dome" (Cupola d'Oro), un ipotetico sistema di difesa missilistica che, secondo alcune ricostruzioni, il precedente Presidente Trump avrebbe voluto estendere dall'Alaska alla Groenlandia.
Ma il "vuoto" sarebbero le vaste isole artiche del Canada, tecnicamente indifendibili da Ottawa. L'idea riportata da alcune fonti? Colmare quel gap con infrastrutture militari, possibilmente attraverso accordi o pressioni commerciali (dazi), aprendo la strada non solo a sistemi difensivi, ma anche a nuove armi offensive puntate verso Est.
È un puzzle geopolitico ad altissimo rischio:
✅ Per gli USA: Controllo totale del fianco nord-americano, deterrenza verso Russia e Cina, accesso a risorse e rotte artiche.
⚠️ Per il Canada: Sovranità compromessa su un territorio immenso che non può presidiare da solo, costretto a scelte difficili tra partnership e sudditanza.
? Per il mondo: Una nuova, potente corsa agli armamenti nell'Artico, con il rischio concreto che trattati cruciali come il New START (controllo armi nucleari) vengano lasciati decadere, aprendo una fase di imprevedibilità globale.
La storia si ripete? Alcuni analisti vedono un parallelismo con lo schieramento dello scudo missilistico USA in Europa orientale, che per anni è stato fonte di gravissime tensioni con la Russia, accusata di nascondere capacità offensive dietro sistemi "difensivi".
Cosa ne pensate?
1. È una mossa strategica necessaria per gli USA in un mondo multipolare conflittuale?
2. È un pericoloso passo verso la militarizzazione di un'area fragile e cruciale per il clima?
3. Il Canada dovrebbe opporsi a qualsiasi presenza militare straniera nel suo Artico, a qualunque costo?
#Geopolitica#Artico#USA#Canada#DifesaMissilistica#GoldenDome#SicurezzaNazionale#Trump#Groenlandia#Russia#Cina
https://www.marx21.it/internazionale/lacquisizione-della-groenlandia-da-parte-degli-stati-uniti-potrebbe-portare-a-un-accordo-sulle-isole-artiche-del-canada/