Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
«جنگ ایران» دگربار نشان داد که تکنولوژی بهتنهایی نمیتواند ژئوپلیتیک را رام سازد و مهار کند. میدان نبرد نه تنها با جنگافزارهای مدرن، بلکه با جغرافیا نیز تعیین میشود. سرنوشت این جنگ چه بسا ممکن است سرانجام به دو گلوگاه ژئوپلیتیکی گره بخورد: تنگه هرمز و بابالمندب.
#IranWar
A War Without a Clear Exit: Iran, the United States, and Israel at Week Five. Read more.
https://borkena.com/2026/04/05/iran-war-a-war-without-a-clear-exit-iran-the-united-states-and-israel-at-week-five/#Iran#Iranwar#usa
🚨🇺🇸TRUMP WEIGHS MASSIVE TROOP SURGE TO IRAN WAR ZONE
🔹 Pentagon considers deploying THOUSANDS more troops as Iran conflict hits day 37 — biggest Middle East buildup since Iraq 2003 ⚔️
🔹 Already ordered: 2,500 Marines aboard USS Tripoli heading to Strait of Hormuz for uranium seizure mission 🚢
🔹 Target: 900 pounds Iranian enriched uranium buried deep underground — Trump calls operation 'very dangerous' 💣
🔹 Public support TANKING: Only 25% of Americans back this war, Pentagon officials dispute intelligence justification 📊
Largest US military presence in Middle East since Bush era — but is America ready for another ground war? 🔥💀
#USNews#IranWar#breaking
@america
Trump says “I agree to suspend the bombing and attack of Iran” Read more.
https://borkena.com/2026/04/07/trump-says-i-agree-to-suspend-the-bombing-and-attack-of-iran/#Trump#Iran#IranWar#iranwar@realDonaldTrump#usa
Guess what?! Roaming through American IT market led us to an Israeli company called Netvision. I took the company details from the web. As you can see, Bushnell's poster was on the printing queue three times. And do not forget, while we are watching all these posts, Iranians are getting killed by peace-bringing bombs from above. 💔
#bushnell
#Iranwar
#Israel
🚨📊TRUMP APPROVAL HITS IRAN WAR LOW — 40% AS GAS SOARS
🔹 Trump approval drops to 40-42% in new March polls — lowest since Iran war began 🇺🇸🇮🇷
🔹 Gas prices surge to $3.96/gallon after Iran blocks Hormuz Strait — up 35% in one month ⛽💰
🔹 Only 38% approve of his Middle East handling while 67% slam cost-of-living response 📈📉
🔹 $100 fill-ups now reality as oil hits $100/barrel — analysts say no relief until mid-2027 😤⛽
🔹 92% of MAGA base still supports Iran strikes but independents demand quick exit strategy 🎯🚁
The pump prices are KILLING his numbers — even loyal voters feeling the pinch 💸🔥
#USNews#TrumpPolls#IranWar
@america
God Save Ethiopia from the Gulf War: The Mechanics of a Fuel-Driven State Collapse. Read more.
https://borkena.com/2026/04/07/god-save-ethiopia-from-the-gulf-war-the-mechanics-of-a-fuel-driven-state-collapse/#Ethiopia#IranWar#fuel