Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🌎 Scientists researching the mysteries of parallel worlds often reference "brane theory," which suggests our universe could be a 3D surface, or 'brane,' floating in higher-dimensional space. In this model, multiple branes—each a universe with its own laws—could exist, and gravity may leak between them, which physicists are testing with experiments at facilities like CERN. ✨
#physics⚡#universe⚡#dimensions
👉subscribe Interesting Planet
👉more Channels
🌎 The concept of "extra dimensions" in physics comes from string theory, which requires at least 10 dimensions for its mathematical consistency. While these extra dimensions could allow for parallel universes, none have been directly detected. Experiments like those at CERN look for signs such as missing energy that might hint at hidden dimensions. ✨
#physics⚡#stringtheory⚡#dimensions
👉subscribe Interesting Planet
👉more Channels
🌎 The concept of higher dimensions beyond the familiar three of space and one of time appears in advanced physics, especially string theory. String theory mathematically requires up to 10 or 11 dimensions to explain gravity and fundamental particles. These extra dimensions are thought to be compact and hidden, possibly curled up at sizes far smaller than atoms. ✨
#dimensions⚡#stringtheory⚡#physics
👉subscribe Interesting Planet
👉more Channels
🌎 In 2022, a study using gravitational wave detectors like LIGO examined whether ripples from colliding black holes hinted at hidden dimensions. The research found no evidence for extra spatial dimensions, setting new constraints on theories that propose parallel universes. ✨
#physics⚡#blackholes⚡#dimensions
👉subscribe Interesting Planet
👉more Channels
🌎 The "brane multiverse" is a scientific idea suggesting our universe might be a three-dimensional "brane" floating in higher-dimensional space. Some versions of string theory propose multiple branes could exist close together, and rare collisions might even trigger new big bangs. The concept arises from efforts to unify gravity with quantum physics. ✨
#multiverse⚡#dimensions⚡#stringtheory
👉subscribe Interesting Planet
🌎 Physicists are searching for evidence of extra dimensions that could exist alongside our three spatial dimensions and time. Experimental efforts, like those at the Large Hadron Collider, look for signs such as missing energy or unusual particle behavior that might indicate the presence of dimensions beyond the familiar four. So far, no direct evidence has been found for extra dimensions. ✨
#physics⚡#dimensions⚡#experiment
👉subscribe Interesting Planet
👉more Channels
Тема шестого дня — картографирование за пределами 2D.
Эту работу подготовил наш коллега @Oreshulya для личного проекта. На карте изображён подводный рельеф небольшого озера Уайтфиш в Канаде. При создании использовалось ПО QGIS для получения картографических данных и Blender 3D для их визуализации.
Основной задачей было показать батиметрические данные в трёхмерном виде, что проблематично сделать с использованием стандартных средств ГИС. Способом изображения для этого была выбрана послойная окраска. Благодаря тому что каждый слой помимо уникального цвета имеет разную высоту в пространстве, создаётся ощущение объёма и глубины, которое на стандартных двумерных батиметрических картах достигается с помощью способа Танака (освещённых горизонталей).
#30DayMapChallenge#Day6#Dimensions#Cartography#GIS