Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
☀️Traders!
📈
A new day brings new opportunities — the market never sleeps, and neither do the smart traders. 🔥
Focus on discipline, patience, and perfect entries today. Remember — profits come to those who wait for the right moment, not every moment! 💰
💰 Stay focused
📊 Trust your strategy
🚀 Let’s make today a winning day!
#TradingMindset#MorningVibes
New week = New opportunities 🚀
Every Monday is a reminder that:
“If yesterday was tough, today is a fresh start.”
In trading, your greatest skills are patience and consistency.
Don’t just trade — plan, learn, and grow.
📈 Stay focused.
💡 Stay disciplined.
🔥 Stay motivated.
Let’s make this week profitable!
💲
#MondayMotivation#BinaryOptions#TradingMindset
☀️Good Morning Traders!
📈
A new day brings new opportunities — the market never sleeps, and neither do the smart traders. 🔥
Focus on discipline, patience, and perfect entries today. Remember — profits come to those who wait for the right moment, not every moment! 💰
💰 Stay focused
📊 Trust your strategy
🚀 Let’s make today a winning day!
#BinaryOptions#TradingMindset#MorningVibes
🌅Good Morning Traders!
It’s Monday — a fresh start, a new week, and a new chance to level up your trading game. 💥
Forget past mistakes; let them guide your strategy, sharpen your focus, and strengthen your discipline.
Stay patient. Stay consistent.
Remember — smart planning and steady execution always beat impulsive moves.
Let’s make this week a profitable one! 🚀
#MondayMotivation#TradingMindset#Discipline#RealBinaryOptions
🪙🎥 The highest state of trading is clarity, not intensity.#TradingMindset
簡單白話的說:
‘’想盡辦法讓自己長期待在市場裡
不要參與槓桿項目,不要被你老師帶單‘’
「你不會是天之驕子,只會是被騙的傻子」
#MarketPsychology#Shorts
#情绪控制#Crypto#心态建议#诈骗宣导
———
⚡️ 在市場中真正的優勢並非「更激烈的操作」,而是更高維度的冷靜、紀律、耐心與客觀的心境,這也是長期成功投資者共同的心法。
✅Chat: @Web3NewsInsight
🦂
👇Tip👇讚 或點擊進行💎資源搜索👇