Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
@RusEmbMalta Press Release
✖️Examples of Actions by the Kiev Regime Undermining Peace Efforts
Following President Trump’s meetings with President Vladimir Putin (Alaska, 15 August) and Vladimir Zelensky (Washington, 18 August), he described the talks as “a good first step” towards ending the conflict. He stressed that Kiev must show flexibility, confirmed Ukraine will not join NATO, and highlighted the importance of territorial compromises along the current line of contact.
👉 Despite these statements, the Kiev leadership – with European backing – continues to obstruct a peaceful settlement:
1️⃣ Refusal to Recognize New Realities
Zelensky (21 Aug): Ukraine will “never legally recognize” Russian control of territories. Yermak & Podolyak echoed this, rejecting compromise.
2️⃣Rejection of Ceasefire
Zelensky announced mass production of long-range Flamingo missiles; later praised strikes into Russian territory as “positive results.”
3️⃣ Language Policy
Zelensky: “We have only one state language – Ukrainian.”
4️⃣Security Guarantees
Zelensky dismissed China as a potential guarantor, while Podolyak demanded deployment of Western missiles capable of striking 2,000 km into Russian territory. NATO Secretary General Mark Rutte confirmed that Western military support and long-term guarantees for Kiev are being discussed.
5️⃣No Readiness for Direct Talks
Zelensky ruled out bilateral talks with Moscow, insisting on a three-party format with Trump.
6️⃣Attacks on Civilian Infrastructure
Attempts to strike nuclear facilities in Smolensk & Kursk, attack on Druzhba oil pipeline (impacting Hungary & Slovakia), and a planned bombing of the Crimean Bridge.
⚠️Conclusion:
The Kiev regime consistently rejects diplomatic resolution, escalates hostilities, undermines dialogue, and employs terrorist methods against civilian infrastructure in Russia.
#KievRegime#GlobalSecurity#MultipolarWorld
Iranian regime promises $25 million for assassination of Trump in mass SMS messages
[Read FullArticle]
@WorldNews#IranNews#TrumpAssassination#GlobalSecurity
Zelenskyy says 10 drone factories have been built worldwide behind Ukraine’s back | Ukrainska Pravda
[Read FullArticle]
@WorldNews#UkraineNews#DroneFactories#GlobalSecurity
U.S. can only confirm about a third of Iran's missile arsenal destroyed, sources say
[Read FullArticle]
@WorldNews#IranMissileArsenal#USNews#GlobalSecurity
China urges US, Israel to stop military action in Middle East, warns of 'vicious cycle'
[Read FullArticle]
@WorldNews#MiddleEastConflict#ChinaUSRelations#GlobalSecurity
Treasury secretary defends U.S. military actions in Iran: 'Sometimes you have to escalate to de-escalate'
[Read FullArticle]
@WorldNews#USIranTensions#MilitaryAction#GlobalSecurity