Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#CANNABIS
Il Parlamento israeliano ha approvato nella lettura preliminare una proposta di legge (presentata da Sharren Haskel, di New Hope) volta a riformare l’industria della cannabis medica, estendendo le possibilità di un suo utilizzo. Nello specifico, in assenza della maggioranza sufficiente per poter approvare una normativa finalizzata alla de-penalizzazione del suo utilizzo a scopo ricreativo, si ambisce a realizzare alcune innovazioni in materia: chi otterrà la licenza da parte del Ministero della Salute sarà legalmente autorizzato a coltivare, distribuire e possedere la cannabis a scopi medici.
Adesso, la proposta sarà sottoposta ad una Commissione parlamentare, che la preparerà per la prima lettura nello Knesset.
👉@giurisprudentia
🌿🇺🇸TRUMP FAST-TRACKS MEDICAL MARIJUANA RESCHEDULING
🔹 Executive order directs Attorney General to expedite rescheduling from dangerous Schedule I to Schedule III classification 📋⚡
🔹 Over $30,000 in criminal penalties reduced to civil fines for possession under 1 ounce 💰
🔹 $43,000 average savings per patient annually on medical cannabis costs with insurance coverage 💊💸
🔹 38 states already have medical programs — federal reform finally catching up to reality 🗺️
This policy shift could reshape American healthcare and criminal justice forever 🔥
#USNews#cannabis
✨ More breaking stories coming soon 🚀
@america
#Germania
❗️ Via libera del governo federale tedesco al documento con le linee guida sulla legalizzazione della #cannabis. Il piano, che deve ancora essere trasformato in proposta di legge e votato dal Parlamento, punta a regolare il consumo e la produzione di cannabis, depenalizzando anche l’uso personale ricreativo entro i 30 grammi
@UltimoraPolitics
Standard Wellness Secures $10M Funding
Standard Wellness has successfully raised $10 million in funding as of December 17, 2024. The company is dedicated to enhancing quality of life by providing safe and easy access to cannabis.
#Funding#Cannabis#Healthcare#QualityOfLife#Investment#StandardWellness#Capital#Access#Wellness#Health
Latest Funding Rounds News
Recent funding highlights include:
- Universal Matter: $20M raised on Dec 16, 2024. Visit
- InterCure: $18.20M on Dec 20, 2024. A leading cannabis company. Visit
- Atmo: $17.58M on Dec 20, 2024, developing AI-based meteorology systems. Visit
- Sitemate: $17.20M on Dec 23, 2024, simplifying industrial workflows. Visit
- Meddipay: $15M on Dec 17, 2024, in health and wellness payment facilitation. Visit
- SignalRank Corporation: $11.55M on Dec 21, 2024, focusing on private market investments. Visit
- Usual Labs: $10M on Dec 23, 2024, transforming tokenized assets into stablecoins. Visit
- Tracer Biotechnologies: $10M on Dec 12, 2024, innovating in ctDNA assays. Visit
- Stipple Bio: $9.48M on Dec 20, 2024, enhancing cellular profiling. Visit
- Mindgard: $8M on Dec 20, 2024, securing AI systems. Visit
#Funding#UniversalMatter#InterCure#Atmo#Sitemate#Meddipay#SignalRank#UsualLabs#TracerBiotechnologies#StippleBio#Mindgard#Cannabis#AI#Technology#Health#Wellness#Software#Investments#Startups#Finance#Innovation