Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
⌚️Smart Devices Are Eating the Accessible Watches Market (under £500)
- While luxury’s moat remains, watchmakers have struggled to build hype for accessibly priced timepieces as consumers increasingly abandon them for smart devices.
- Popular upstart brands like Mvmt and Daniel Wellington signal that success in this price category is possible with the right marketing.
- Brands need to focus on their history and heritage: reissues of iconic watches like the original G-Shock have performed well with consumers.
A drop in demand for cheaper watches is causing trouble for Switzerland’s manufacturing base and Swiss watch companies specialising in watches under £500. Since 2015, the number of Swiss watches being exported has declined by a third, per the Federation of the Swiss Watch Industry, and most of that shrinkage has been in watches that cost under 200 CHF (£164). Exports are approaching the lows seen in the mid-1980s when Japanese quartz technology brought a raft of cheaper competitors for established brands.
#smartwatch
𝕭𝖊𝖓
🦅@PerspectiveIX via VogueBusiness.
Something is happening... in case it wasn’t clear...
#Smartphone#SmartWatch
🚀@PerspectiveIX
👻http://prs.pctvix.co/SnapchatIX
Do you own a Smart Watch?
👍 Yes
👎 No
⌚️Apple vs Samsung: The Smart Watch Edition
Based on IDC estimates, #Samsung has a lot of ground to make up if it wants to challenge #Apple’s dominant position in the #smartwatch market. In 2017, the Cupertino-based company shipped 17.7 million watches compared to Samsung’s 3.6 million.
🚀@PerspectiveIX
📖 via Statista: prs.pctvix.co/2Ou1tfC
❓ Do you own a smartwatch?
💥Reloj inteligente Garmin Negro 45 mm
Potencia tus entrenamientos con tecnología de vanguardia para un invierno lleno
✅OFERTA: 241.81€
❌ Antes: 449.99€
💰Ahorras un 46%🔥
Monitorización completa de tu actividad física, diseño resistente al agua y cone
👉 Hazte con el tuyo y empieza a superarte hoy mismo
#rebajas#smartwatch#deporte#descuentos#garmin
🛰️Oferta publicada en Deporte y Outdoor
💥Smartwatch Garmin Vívoactive 5 Blanco
Potencia tu entrenamiento con GPS y funciones de salud avanzadas. No pierdas la
✅OFERTA: 180.9€
❌ Antes: 299.99€
💰Ahorras un 40%🔥
Monitoriza tu salud, mejora tu rendimiento y disfruta de una batería de larga du
👉 Hazte con el tuyo y mantente en forma este invierno
#rebajas#smartwatch#salud#formafisica#descuentos
🛰️Oferta publicada en Deporte y Outdoor
⌚️Smartwatch Market 2Q21
The global #smartwatch market grew 27% YoY in Q2, per Counterpoint Research. Obviously, #Apple remains on top, but its market share did slip from 30.1% in Q2 2020 to 28% today.
Meanwhile, #Samsung saw its slice of the pie expand from 6.8% to 7.6%—an upward trend that could continue thanks to its newly unveiled #GalaxyWatch 4, made in partnership with #Google.
All Credits: Counterpoint Research
🦅@iXDaily x @perspectiveix
⌚ ¡Jueves de bombazos en AliExpress!
Hoy tenemos descuentos que no vas a creer. El chollo estrella es el Reloj Inteligente Xiaomi Ultra 2 con pantalla AMOLED rebajado un 84% (se queda en 31,99€). También destacamos un gran juego de herramientas súper completo por solo 4,68€ y ropa cómoda y deportiva para mujer a precios mínimos. ¡Corre que vuelan! 🧰👟
👇 Selección del día:
🔥 Reloj Inteligente Xiaomi IOS Ultra 2 AMOLED por 31,99€ (-84% dto)
🔗https://s.click.aliexpress.com/e/_EIizPh2
🔥 Gran Juego de Herramientas Mecánicas para Coche por 4,68€ (-56% dto)
🔗https://s.click.aliexpress.com/e/_ExuyzQ8
🔥 Chaquetas Ajustadas de Plumón de Pato Mujer por 18,59€ (-51% dto)
🔗https://s.click.aliexpress.com/e/_Ewidz8g
🔥 Zapatos de Punta Ancha Mujer Suela Suave por 15,19€ (-53% dto)
🔗https://s.click.aliexpress.com/e/_Ex73KUk
🔥 Mallas Elásticas con Bolsillos de Mujer por 11,26€ (-54% dto)
🔗https://s.click.aliexpress.com/e/_Eu4vjQy
🔥 Sudadera Capucha Estampado Náutico Mujer por 8,88€ (-56% dto)
🔗https://s.click.aliexpress.com/e/_EQPYNIk
#AliExpress#Smartwatch#Xiaomi#Herramientas#Ofertas#Ahorro
💥XIAOMI Watch S4 Bluetooth
El regalo perfecto para los amantes del deporte
✅OFERTA: 90.0€
❌ Antes: 159.99€
💰Ahorras un 44%🔥
Monitoriza tu actividad física de forma profesional y mejora tu rendimiento
👉 Hazte con él y sorprende esta Navidad
#tecnologia#smartwatch#deporte#monitorcardiaco#pantallaamoled#ofertas#navidad#viral
🛰️Oferta publicada en Tecnología
💥Reloj Inteligente XIAOMI Redmi Watch 5
El regalo perfecto para mantenerte conectado y activo
✅OFERTA: 56.58€
❌ Antes: 109.99€
💰Ahorras un 49%🔥
Pantalla AMOLED vibrante, larga duración de batería y múltiples funciones deport
👉 Hazte con él y comienza a disfrutar
#smartwatch#tecnologia#xiaomiredmiwatch5#monitorcardiaco#gps#ofertas#navidad
🛰️Oferta publicada en Tecnología
💥Reloj Inteligente Ddidbi Militar
Potencia tu entrenamiento con tecnología de vanguardia
✅OFERTA: 32.99€
❌ Antes: 129.99€
💰Ahorras un 75%🔥
Registra más de 110 modos deportivos y monitorea tu salud en tiempo real
👉 Haz tuya la revolución smartwatch
#rebajas#relojinteligente#smartwatch#monitorderitmo#pulseraactividad#moda#belleza#ofertas
🛰️Oferta publicada en Moda y Belleza
💥Smartwatch HUAKUA Sin Bluetooth
Actívate sin distracciones
✅OFERTA: 29.99€
❌ Antes: 49.99€
💰Ahorras un 40%🔥
Registra tus actividades sin depender del móvil
👉 Hazte con él ahora
#rebajas#smartwatch#pulseradeactividad#monitordecalorias#impermeable#temporizador#descuentos#rebajasdeinvierno
🛰️Oferta publicada en Deporte y Outdoor