Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
The sunrays taking;
All the darkness away,
Love taking all hatred away,
Miniature hopes in shapes of stars,
Now subsiding in beautiful destiny,
Happiness taking all the pain away.
In midst the beautiful world,
I laid here,
Breathless,
My sould taken away by you,
My heart given to beat in someones
Else's cage,
My body drifted with fire,
My voice taken away by deafening silence,
My memories now, washed away,
Fading away with new ones.
This is how,
A beautiful day began,
Changing my life,
To be dreadful forever,
In midst the beautiful world,
I laid here as a dead lover.
#tyler#review
She's like a poem,
Waiting to be read.
She's like a song,
Waiting to be sung.
She's like a melody,
Waiting to be heard.
She's like a book,
Waiting to be understood.
She's like a dance,
Waiting to be performed.
She's like a beauty,
Waiting to be cherished.
She's like art,
Waiting to be crafted.
She's you,
Waiting to be found.
She's you,
Waiting to be loved.
She's not just a girl,
She's within all of you,
She resides somewhere inside,
Somewhere the golden rays don't reach,
Somewhere the silver shine doesn't work,
Somewhere in you,
She stays,
Waiting to be acknowledged.
#tyler#review
She's like a poem,
Waiting to be read.
She's like a song,
Waiting to be sung.
She's like a melody,
Waiting to be heard.
She's like a book,
Waiting to be understood.
She's like a dance,
Waiting to be performed.
She's like a beauty,
Waiting to be cherished.
She's like art,
Waiting to be crafted.
She's you,
Waiting to be found.
She's you,
Waiting to be loved.
She's not just a girl,
She's within all of you,
She resides somewhere inside,
Somewhere the golden rays don't reach,
Somewhere the silver shine doesn't work,
Somewhere in you,
She stays,
Waiting to be acknowledged.
#tyler#review
During a dreadful night,
I managed to put up a fight.
Maybe the strong me died,
And weak me survived.
The constant voices in my ears,
Here I am living in my fears.
Like a painful reminder of that night,
Where I lost a outnumbered fight.
Wondering if I am even right,
While holding myself tight.
The night is long dead,
Here my tears still wetting my bed.
That dreadful night,
The cause of my fright.
These thoughts make me shiver,
The fear making me quiver.
My painful screams,
Still haunting my dreams.
Maybe the strong in me died,
And weak me survived.
I haven't given up the fight,
Because I know,
I can still make it right.
#tyler#review
The correspondence of Tyler Robinson, a suspect in the murder of Charlie Kirk, with his transgender lover, with whom he lived, has been published. The name of the roommate is not mentioned.
#correspondence#tyler#robinson#suspect
#Trump#Democrats
👂More on Trump's Ear ⚠️