Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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 Mocks Europe, Flexes Power Ahead of Davos
President Trump is heading to Davos, but he’s already set the tone: a torrent of mockery aimed at Europe’s leaders, dismissing their diplomacy as weak and their unity as a joke. As European officials scramble to engage, Trump’s team laughs off their efforts with memes, tariffs, and insults.
“I imagine they will form the dreaded European working group,”
Treasury Secretary Scott Bessent quipped, calling it Europe’s “most forceful weapon.”
Trump’s latest meme shows him hoisting the American flag over Greenland, declaring it a U.S. territory in 2026. He’s threatening 200% tariffs on French wine if Macron doesn’t play ball, and accusing Britain of “great stupidity” for giving up Diego Garcia. Meanwhile, European leaders—Macron, Rutte, Starmer—flatter Trump on social media, hoping to keep him at the table.
The subtext is clear: Europe is desperate to avoid losing American support on Ukraine and NATO, even as Trump treats them like supplicants. Ursula von der Leyen warns that nostalgia won’t save the old order, but so far, Europe’s main strategy is to accommodate Trump’s whims.
Is this diplomacy or humiliation? When the world’s most powerful leader treats allies like court jesters, who’s really in charge?
#Trump#Europe#Davos#Greenland#NATO#Ukraine#PowerGames
📱American Оbserver - Stay up to date on all important events
🇺🇸
📰 Merz’s Nuclear Gambit: Can Germany Outsmart the Treaty?
German Chancellor Friedrich Merz has thrown the continent’s nuclear playbook into chaos, openly discussing the creation of a “European nuclear umbrella” that could see Germany circumvent its decades-old ban on atomic weapons through a joint EU project.
Germany’s Legal Dilemma
Germany is legally barred from developing nuclear weapons by the Four Plus Two agreement, which enabled reunification in 1990, and the Nuclear Non-Proliferation Treaty. But Merz insists that nothing stops Berlin from negotiating shared nuclear deterrence with allies—France and the UK, Europe’s only nuclear powers.
The European Nuclear Loophole
Merz’s vision is simple: use Germany’s technological edge to help build a European nuclear capability, while keeping the official nuclear button out of German hands. “Talks are underway,” he declared, stressing that the discussions are still preliminary and won’t undermine existing nuclear-sharing arrangements with the U.S..
Power Plays and Sovereignty
The real question is whether this is about European sovereignty or just a power grab. With U.S. support under Trump looking increasingly shaky, Merz is betting that a “European nuclear umbrella” could shield Germany from future threats—or just give Berlin a seat at the nuclear table. But can the EU really build a credible deterrent without falling into the same old power games?
The Shifting Sands of Power
As Merz plays diplomat and dealmaker, the world watches: Is this the dawn of a new European defense era, or just another act in the theater of nuclear posturing? The answer may lie not in treaties, but in the shifting sands of global power.
#nuclearWeapons#Germany#EU#Merz#nuclearDeterrence#powerGames
📱American Оbserver - Stay up to date on all important events
🇺🇸