Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Highest quality soft crates from Sweden 🇸🇪 not China 🇨🇳 junk and not excessive cost ,
the usual 5 sizes are available now and on stock…
60cm 59€
70cm 69€
80cm 80€
105cm 95€
120cm 110€
Available at the following upcoming big CACIB shows
Tallinn Estonia 🇪🇪 August
Palanga Lithuania 🇱🇹 September
Komarom Hungary 🇭🇺 October
…Or
you can order online at Kennel.Ai
…Register your new puppies or pet dogs for additional discounts
https://kennel.ai/login
#$dogs #$bone #petdognft#decentralised
Have a look at the Kennel.ai website blog to learn more about dogs
https://kennel.ai/blogs
Also watch our YouTube channel
https://www.youtube.com/@Dogstoken
#doghealth#dogblog#petdogNFT #$DOGS
Have a look at the Kennel.ai website blog to learn more about dogs
https://kennel.ai/blogs
Also watch our YouTube channel
https://www.youtube.com/@Dogstoken
#doghealth#dogblog#petdogNFT #$DOGS
Have a look at the Kennel.ai website blog to learn more about dogs
https://kennel.ai/blogs
Also watch our YouTube channel
https://www.youtube.com/@Dogstoken
#doghealth#dogblog#petdogNFT #$DOGS
Have a look at the Kennel.ai website blog to learn more about dogs
https://kennel.ai/blogs
Also watch our YouTube channel
https://www.youtube.com/@Dogstoken
#doghealth#dogblog#petdogNFT #$DOGS
Direct from UK manufacturer
Heavyweight rubber back VetBed
Buy now before the Winter ⛄️
Warm , Machine Washable 50 colour choices
Buy full roll for maximum discount
Free home delivery ;
Estonia 🇪🇪 Finland 🇫🇮 Latvia 🇱🇻
Lithuania 🇱🇹 Poland 🇵🇱 Slovakia 🇸🇰
Czech Republic 🇨🇿 Hungary 🇭🇺
Croatia 🇭🇷
Payment by bank crypto or to the delivery 📦 driver 🚚
www.Kennel.Ai
#VetBed#Kennel.Ai #DogBreeder#PetDogNFT
Direct from UK manufacturer
Heavyweight rubber back VetBed
Buy now before the Winter ⛄️
Warm , Machine Washable 50 colour choices
Buy full roll for maximum discount
Free home delivery ;
Estonia 🇪🇪 Finland 🇫🇮 Latvia 🇱🇻
Lithuania 🇱🇹 Poland 🇵🇱 Slovakia 🇸🇰
Czech Republic 🇨🇿 Hungary 🇭🇺
Croatia 🇭🇷
Payment by bank crypto or to the delivery 📦 driver 🚚
www.Kennel.Ai
#VetBed#Kennel.Ai #DogBreeder#PetDogNFT
Direct from UK manufacturer
Heavyweight rubber back VetBed
Buy now before the Winter ⛄️
Warm , Machine Washable 50 colour choices
Buy full roll for maximum discount
Free home delivery ;
Estonia 🇪🇪 Finland 🇫🇮 Latvia 🇱🇻
Lithuania 🇱🇹 Poland 🇵🇱 Slovakia 🇸🇰
Czech Republic 🇨🇿 Hungary 🇭🇺
Croatia 🇭🇷
Payment by bank crypto or to the delivery 📦 driver 🚚
www.Kennel.Ai
#VetBed#Kennel.Ai #DogBreeder#PetDogNFT