Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🚀🚀Raining Profits in the Premium Group
🎯🎯#FLOCK/USDT has covered all the targets to give an amazing profit of 142% for all Premium Members
👁🗨Contact @futurechief to enter the premium group & make daily gains on Futures as well as Spot Market
☑️☑️Below you will see the Futures Premium Signals Results for (24th February 2026)
🚀#FLOCK-USDT - 142% profit
🚀#ESP-USDT - 24% profit
❌
✅✅Net Profit = 166% Profit
👇🏻Signals Summary
➕Total Signals Sent out - 02
✔️Profitable Signals - 02
✖️Total Signals Lost - 00
◼️Trade cancelled without being executed - 00
✅✅Net Profit - 166% Profit
👁🗨Contact @futurechief to enter the most profitable Futures Premium Signal Group
Flock Secures $3M in Funding
Web3 AI training firm Flock has successfully raised $3M in a strategic funding round led by Digital Currency Group (DCG). Notable participants included Lightspeed Faction, Animoca Brands, Fenbushi Capital, Gnosis DAO, Bas1s Ventures, A41, and GSR Markets LTD.
#Web3#AI#Funding#Flock#DigitalCurrencyGroup#LightspeedFaction#AnimocaBrands#FenbushiCapital#GnosisDAO#Bas1sVentures#A41#GSRMarkets
Innovative Startups Raise Millions in Funding
A roundup of recent startup funding successes:
- Xiao Shangquan: $4.12M on Dec 16 for an ad investment platform for local merchants. Learn more
- Takumi Giken Kogyo: $3.26M on Dec 17, aims to innovate manufacturing while addressing social issues. Learn more
- FLock.io: $3M on Dec 19, building a decentralized privacy-preserving AI solution. Learn more
- Proxgy: $3M on Dec 26, creating a comprehensive ecosystem for global industries. Learn more
- RadioNano Therapeutics: $954.66K on Dec 25, advancing new cancer treatments from Kyoto University. Learn more
- Abastores: $788.78K on Dec 16, legal service for suppliers. Learn more
- EduCare: $778.73K on Dec 16, financing education and career support. Learn more
- Inyanga Marine Projects: $640.27K on Nov 29, specializing in tidal array technology. Learn more
- Kloutit: $559.69K on Dec 19, using AI to enhance chargeback defenses. Learn more
- EnviraBoard: $538.97K on Nov 30, focused on carbon-negative building materials. Learn more
#Funding#Investment#XiaoShangquan#TakumiGikenKogyo#FLock#Proxgy#RadioNano#EduCare#InyangaMarine#Kloutit#EnviraBoard#AI#Crypto#VC