Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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 disappearance of the Sodder children in 1945 remains unsolved. Five siblings vanished after a house fire in Fayetteville, West Virginia. Investigators found no remains in the ash, and sightings were later reported but never verified. A billboard seeking answers stood along Route 16 for decades. ✨
#history⚡#disappearance⚡#mystery
👉subscribe Interesting Planet
🌎 In 2009, French aircraft Air France Flight 447 disappeared over the Atlantic during a flight from Rio de Janeiro to Paris. All 228 people on board died. The plane's wreckage was not found for nearly two years, when deep-sea searches located the main debris field at a depth of 3,900 meters. ✨
#aviation⚡#disappearance⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 In 1815, the British brig HMS Rosalie was found abandoned and drifting near the Bahamas. The ship’s sails were set, and cargo untouched, but not a single crew member was found onboard. Official records note that the ship’s logbook and personal belongings were still present when discovered. ✨
#disappearance⚡#maritime⚡#mystery
👉subscribe Interesting Planet
🌎 In 1973, Australian pilot Frederick Valentich disappeared while flying a Cessna 182L over Bass Strait. During radio contact, he reported a strange, unidentified craft circling his plane before transmission was lost. Despite a large search, neither Valentich nor his aircraft were ever found. ✨
#disappearance⚡#aviation⚡#australia
👉subscribe Interesting Planet
👉more Channels
🌎 In 1872, the Mary Celeste was found adrift in the Atlantic Ocean—its crew vanished without a trace, leaving food, cargo, and the ship untouched. This unsolved maritime mystery has puzzled historians ever since. ✨
#disappearance⚡#ship⚡#mystery
👉subscribe Interesting Planet
🌎 In 1925, British explorer Percy Fawcett vanished in Brazil's Amazon rainforest while searching for the lost city of "Z." Fawcett, his son, and a companion were last seen near the Upper Xingu River. Despite dozens of rescue missions over decades, no confirmed trace of the expedition was ever found. ✨
#amazon⚡#disappearance⚡#exploration
👉subscribe Interesting Planet
👉more Channels