Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Caramelized Onion Pasta
Ingredients:
Oven:
*300 g shallots
*300 g vegan cream cheese
*60 ml maple syrup
*200 g smoked tofu
*salt and pepper
*Oil as desired
Aside from that:
*350g pasta
*200 g dried tomatoes
*1 bunch of fresh wild garlic
*60 ml pasta water
#paste
@dishes
Rice Noodle Spring Salad
Ingredients:
*1 carrot
*100 g fresh red cabbage
*1/2 cucumber
*1/2 red onion
*1 mango
*250 g rice noodles
Peanut sauce:
*2 cm ginger
*2 cloves of garlic
*200 g peanut butter
*20 ml sesame oil
*50 ml maple syrup
*50 ml soy sauce
*150ml water
Toppings:
Chili flakes
Coriander, mint
peanuts
#paste
@dishes
You Need To Taste This Green Goddess Salad With Watermelon & Pasta
Ingredients:
*200 grams of watermelon
*100 grams of cucumber
*200 grams of pasta
Dressing:
*80 grams of spinach
*1/2 bunch basil
*1 clove of garlic
*1/2 onion
*50 grams of peas
*40ml oil
*25ml water
*1 tbsp vinegar
*1 tsp salt
*40 grams of walnuts
*juice of a lemon
*1 tbsp yeast flakes
*pinch of pepper
toppings:
Walnuts, Basil, Chili Flakes
#paste
@dishes
Pasta Alla Vodka with Pancetta🧀
Ingredients:
*350g. Rigatoni pasta (Can be replaced with penne pasta)
*2 Tbsp Olive oil
*150g. diced Pancetta
*2 Shallot onion, finely chopped
*3 Garlic cloves, finely chopped
*1/2 Tsp Red-Chilli flakes
*1/2 Tsp dried Oregano
*1/2 cup Vodka
*1 cup Tomato sauce
*1/4 cup Tomato paste with basil pesto
*2 cup Heavy cream
*1/4 cup Parmesan cheese, plus more for serving
*1 tablespoon roughly chopped fresh Basil
*2 tablespoons roughly chopped Italian Parsley
#paste
@dishes
ROASTED RED PEPPER PASTA! 🌶️
Ingredients:
* 400 g. Giant Fusilli Pasta
* 4 Red Bell Peppers
* 2 Shallot onion
* 1 head Garlic
* Olive oil
* 1 cup Heavy Cream
* Red chili flakes
* Italian herbs
* 1 tbsp Tomato paste
* 1 tbsp Butter
* Salt/Pepper
#paste
@dishes