Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#TIIF2025#Agenda#11th_June
Panel session: Investor Protection: The New Investment Law, International Arbitration, and Domestic Court System
Venue: Room Kokand
Time: 16:00-17:00
Join Live broadcasting: YouTube
#TIIF2025#Agenda#11th_June
Panel session: Karakalpakstan’s Economic Development Strategy: Present Realities, Growth Dimensions, and Future Opportunities
Venue: Room Bukhara
Time: 16:00-17:00
Join Live broadcasting: YouTube Uz
Join Live broadcasting: YouTube En
#TIIF2025#Agenda#11th_June
Panel session: Privatization: Plans, Approaches, and Achievements
Venue: Room Khiva
Time: 14:00-15:00
Join Live broadcasting: YouTube Uz
Join Live broadcasting: YouTube En
#TIIF2025#Agenda#11th_June
Panel session: Uzbekistan as a Strategic Hub for Critical Raw Materials: Investment Opportunities Across the Value Chain
Venue: Room Kokand
Time: 14:00-15:00
Join Live broadcasting: YouTube
#TIIF2025#Agenda#11th_June
Panel session: Global Trade Fragmentation and Neo-Protectionism: Lessons from the Past, Current Challenges and Implications for Central Asia’s Regional and Global Value Chain Integration Efforts
Venue: Room Samarkand
Time: 14:00-15:00
Join Live broadcasting: YouTube
#TIIF2025#Agenda#11th_June
Panel session: Journey of TBC as a Market Disruptor Shaping Online Banking in Uzbekistan
Venue: Room Kokand
Time: 12:00-13:00
Join Live broadcasting: YouTube
#TIIF2025#Agenda#11th_June
Panel session: Ceasing Water Resources: Solutions, Strategies, and State Priorities
Venue: Room Khiva
Time: 12:00-13:00
Join Live broadcasting: YouTube Uz
Join Live broadcasting: YouTube En
#TIIF2025#Agenda#11th_June
Panel session: IT Sector and AI: Empowering Youth to Drive Innovation and Develop World-Class Solutions
Venue: Room Bukhara
Time: 12:00-13:00
Join Live broadcasting: YouTube Uz
Join Live broadcasting: YouTube En
#TIIF2025#Agenda#11th_June
Panel session: Global Brands as Catalysts: Enhancing National Investment Appeal through Luxury and Innovation
Venue: Room Samarkand
Time: 11:00-12:00
Join Live broadcasting: YouTube