Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🌎 Southern China’s Stone Forest, or Shilin, is a dramatic landscape of towering limestone pillars shaped by both natural erosion and centuries of quarrying. Human mining over the last thousand years has altered parts of this ancient karst region, creating new rock formations and open spaces alongside original spires. ✨
#geology⚡#humanimpact⚡#landscapes
👉subscribe Interesting Planet
👉more Channels
🌍 Cities often create "urban heat islands," where temperatures are higher than surrounding areas due to concrete, asphalt, and less greenery. This effect can raise cities’ temperatures by several degrees. ✨
#urbanization⚡#temperature⚡#humanimpact⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌎 One of Earth's largest artificial lakes, Lake Volta in Ghana, was created in the 1960s by damming the Volta River. Spanning about 8,500 square kilometers, it supports fisheries and transportation but submerged forests and displaced over 78,000 people during its construction. ✨
#humanimpact⚡#reservoirs⚡#Africa
👉subscribe Interesting Planet
👉more channels Channel list
🌎 The Florida Everglades, once a vast slow-moving river system, has been dramatically altered by canals, levees, and drainage for agriculture and cities. Over 50% of the original wetlands have been lost since the early 20th century, reducing habitat for species like the Florida panther and snail kite. ✨
#Everglades⚡#wetlands⚡#humanimpact
👉subscribe Interesting Planet
👉more Channels