Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
If it’s painful for you to criticize your friends, you’re safe in doing it; if you take the slightest pleasure in it, that’s the time to hold your tongue.
– Alice Miller
#friendship@quietworld🍃
As you get older real friendships don’t mean you see each other everyday. In fact some of the realest friends barely see each other, if you both are really out chasing your bags, tryna better your futures, you probably won’t see each other as often.
#friendship@quietworld🍃
Dear folks, this is a translation of one famous poem of one famous poet into English.
Can you please review it and let me know, if it sounds correct, or does it contain enything weird, odd ?
/********************************************/
I like to feel that I'm not sick with you
I like to know that sickness yours is yours not mine
That heavy ball of earth won’t stray off from its course
Away from our footprints , fading in sunshine
I love that I could funny be
Bewildered, clumsy , not wordplaying
not turning red upon sleeves touching game
not turning pale when see you on your knees
I love to see you hugging someone else
Before my eyes , reposefully and calmly
Not sending me to fire glowing hell
To burn forever for not kissing me , my darling
I like that mentioning my name is not your habit
That tender name you don't utter day-and-night in vain
That no one's gonna sing Hallelujah on our wedding
In silence of the church, one sunny autumn day
Thank you for love, with all your heart and soul
That brings me peace at night, unconscious, unaware
Thank you for rare meetings if at all
So nice, That never in the moonlight do we stroll
So great that sun warms not us, soaring high elsewhere
So pity, that I am not sick with you
So bad, that sickness yours is yours not mine
#review
#friendship