Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🌍 The boundary where the Earth's solid land meets the sea—called the coastline—is constantly changing. Waves, tides, and storms reshape these edges every day, making coastlines dynamic and ever-shifting. ✨
#geography⚡#coastlines⚡#change⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Satellite data show that global sea levels are now rising about 3.4 millimeters per year, speeding up since the 1990s and threatening low-lying coasts with accelerated erosion. ✨
#coastline⚡#climate⚡#change⚡#oceans⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Melting permafrost in Arctic regions is releasing ancient greenhouse gases like methane, accelerating climate change and threatening traditional ways of life for local communities. ✨
#permafrost⚡#climate⚡#change⚡#methane⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Desertification, the spread of deserts into once-fertile land, now threatens over a third of Earth’s land surface, endangering food security for millions worldwide. ✨
#desertification⚡#climate⚡#change⚡#land⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
New Book Explores Optimism in AI Future
Reid Hoffman, co-founder of LinkedIn, releases his book *Superagency: what could go right with AI future*. Unlike dystopian views, Hoffman emphasizes a proactive approach to building a positive future with AI. He discusses the evolution of technology's role in society, the importance of agency in the face of AI, and the need for updates in social contracts. The book reflects on history, addressing both fears and potential benefits AI can bring. Full details available here.
#AI#Tech#ReidHoffman#Future#Blockchain#Metaverse#Innovation#Autonomy#SocialChange#Privacy#Agency#Technology#Data#LLM#Community#Change#Trends
Need of Organization 😂
#camurshid#ca#icap#ca_murshid#castudents#camemes#icaistudents#charteredaccountant#charteredaccountancy#charteredaccountants#icaistudents#camemes#icaistudents#charteredaccountant#charteredaccountancy#charteredaccountants#icaistudents#camemes#icaistudents#charteredaccountant#charteredaccountancy#charteredaccountants#icaistudents#camemes #icaistudents#charteredaccountant #icaistudents #camemes#icaistudents #auditor#auditors#auditorslife#change#organization