Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🗓December 3 marks the birthday of Huberte Rupert (1919–2005), a South African philanthropist and art enthusiast whose legacy shaped cultural and social development in the country. 🎨💛🇿🇦
She co-founded the Rupert Museum and supported numerous initiatives in education, healthcare, and the arts.
🖼 The Rupert Museum houses a remarkable collection of modern South African art from the 1940s to the early 2000s. It is located in Stellenbosch, just 50 km east of Cape Town.
Her husband, Anton Rupert, was a prominent South African businessman.
#SouthAfrica#Art#Culture#Philanthropy#HuberteRupert#RupertMuseum#Stellenbosch
🗓3 декабря – день рождения Хуберте Руперт (1919–2005), южноафриканской филантропки и ценительницы искусства, которая внесла огромный вклад в культурные и социальные проекты ЮАР. 🎨💛🇿🇦
Она стала соосновательницей Музея Руперта и поддержала множество инициатив в сфере образования, здравоохранения и искусства.
🖼Музей Руперта хранит впечатляющую коллекцию современного южноафриканского искусства 1940-х — начала 2000-х годов. Он расположен в Стелленбоше, в 50 км к востоку от Кейптауна.
Её муж, Антон Руперт, был известным южноафриканским бизнесменом.
#ЮАР#Искусство#Культура#Филантропия#HuberteRupert#RupertMuseum#Стелленбош#Руперт
🎂 October 4 — Birthday of Anton Edward Rupert (1916 – 2006), South African businessman, philanthropist, and conservationist.
🏛 Museums in South Africa connected to his legacy:
• Rupert Museum (Stellenbosch) — home to one of the most important private collections of 20th-century South African art, assembled by Rupert and his wife Huberte.
• La Motte Museum — located on the family’s wine estate, known for its collection of Pierneef works and Cape Dutch cultural heritage.
• Hester Rupert Art Museum (Graaff-Reinet) — named after Rupert’s mother, showcasing works of South African artists from the mid-20th century.
• Jan Rupert Art Centre (Graaff-Reinet) — a venue for rotating exhibitions under the Rupert Art Foundation.
• Franschhoek Motor Museum 🚗 — a world-class collection of automobiles, motorcycles, and bicycles spanning over 100 years of motoring history, founded by Rupert and later expanded by his son Johann.
🕊 Anton Rupert left a remarkable cultural and environmental legacy, bridging business, art, and nature conservation.
#AntonRupert#SouthAfrica#RupertMuseum#Art#Culture#Heritage#Philanthropy#MotorMuseum