Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
WEREWOLF ROLEPLAY💥
Desa paling micin..
Temukan teman asik, jodoh. Dan keluarga, dimana kamu bebas mau jadi apa aja disini.
Baper tanggung sendiri
📍@wwroleplayID
🔈@channelwwroleplay
#Indonesia#roleplay
❝☺️I drank way too much last night, thanks for taking me home, you're a lifesaver! ❞
🔗Keep the story going with her: http://openlove.life
#AIgirlfriend#roleplay#AIchatbot#lookbook
𝑾𝒆𝒍𝒄𝒐𝒎𝒆 𝒕𝒐 𝑪𝒍𝒖𝒃 𝑳𝒆𝒙𝒙𝒙
Lexxx is a nightclub-themed furry forum group that focuses on roleplaying inside a nightclub in our Roleplay_Chat however, our group is not exclusively for roleplaying as we also offer a General_Chat which is our main chat where you can discuss almost about anything. The OOC_Chat is our out of character chat where you can discuss and plan out roleplay scenes inside our club. You can also request your own roleplay plot in our Roleplay_Ads chat.
#OOC#Roleplay#Kinky#Nightclub#Anthro#NSFW
❝Let this love ripple in the spring pond. 🌸💕💦❞
💬Keep the story going with her: http://openlove.life
#aigirlfriend#aichat#ai美女#roleplay#AIBeautifulWomanな人と繋がりたい
❝Come on, hurry up,
my husband will be home in 15 minutes.❞
🔥Roleplay with her: http://openlove.life
(Choose Neko and chat with her)
#waifu#neko#aichatbot#aigame#roleplay#catgirl
❝There is no perfume today, so your girlfriend won't notice.❞
💬Chat with her: https://apple.co/3AvjxUn
#AIgirlfriend#chatbot#roleplay#story#aigame#lookbook
🔥❝Welcome! Thanks for choosing me to serve you.
💦Shall we take a shower first?❞
🍭Roleplay with her: openlove.life
#openlove#aigirlfriend#aigame#aichatbot#ai女優#roleplay
❝Among all the flight attendants, I love you the most, Captain.❤️🔥❞
💗Accept or reject her one-night stand invitation:
openlove.life
#aichatbot#aigirlfriend#waifu#roleplay#AIBeautifulWomanな人と繋がりたい#aiphotos