Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Xalqaro xotin-qizlar kuni bilan! 🥳
Aziz ayollar, sizni ushbu ajoyib bahor bayrami bilan tabriklaymiz, doimo gullar singari atrofdagilarni o‘z go‘zalligingiz va nafosatingiz bilan quvontirib yuring! 🥰
Barcha qiyinchiliklar sizni chetlab o‘tsin, qalbingizdagi mehr esa yaqinlaringizni va oila a'zolaringizni iliqlik bilan to‘ldirsin. 🫶
Biz sizni yaxshi ko‘ramiz, Kalleh jamoasi ❤️
➖
С Международным женским днем🥳
Милые дамы, поздравляем вас с этим чудесным весенним праздником и желаем, чтобы вы всегда, подобно цветам, радовали всех окружающих своей красотой и нежностью🥰
Пусть все невзгоды обходят вас стороной, а доброта сердца согревает родных и близких🫶
Мы вас любим, команда Kalleh❤️
#kalleh#8march
🎙 President of the Russian Federation Vladimir Putincongratulated the women of Russia on International Women’s Day, celebrated on March 8.
💬Dear women of Russia!
From the bottom of my heart, I congratulate you on International Women’s Day!
In our country, this wonderful holiday is traditionally filled with special warmth and sincerity. Today, words of love, gratitude and respect are heard everywhere. Our men express their appreciation to their mothers, wives, grandmothers, daughters, sisters, friends and colleagues, letting them know how much they are cherished and how deeply their contributions are valued, both at home and in the workplace, where they often take on complex professional challenges.
You truly do it all: taking care of children and scoring outstanding achievements in various fields, embodying both strength and grace, courage and tenderness, and winning us over again and again with your beauty and charm. You inspire men to strive for greatness, encouraging them to do better, to take bold steps and to be the true defenders of their families and homes, and our Motherland.
You hold within you life’s greatest miracle: the gift of bringing new life into the world. The tenderness and generosity of a mother’s heart and the warmth of a mother’s love transform the world and make it a better place. Motherhood is both an immense joy and a profound responsibility. We are fully aware of this and will continue to do our utmost so that mothers and families with children, especially large families, receive the support they need and see that their interests are always in the focus of the government’s attention.
My warmest words go to the women who are in places where it is most difficult right now, the participants in the special military operation. You are working in different spheres, including in field hospitals and on the front lines, doing your combat duty with distinction.
I would also like to say a few words for the women whose dear ones – husbands, fathers, brothers and loved ones – are defending the future of our country. Your heartfelt support and unfailing care, love and loyalty empower our men, strengthening their morale and the unwavering belief that the truth – and hence victory – is on our side.
Dear women!
We know that so much in life depends on you, on your talents, creative energy, love, and utmost responsibility with which you undertake any job. Once again, we are in awe of your beauty, kindness and grace.
I would like to wish success, health, well-being, and all the best to you and your loved ones. May you always find happiness alongside those you hold dear.
💐 Happy International Women’s Day!
#8March#InternationalWomensDay
🎙 President of the Russian Federation Vladimir Putincongratulated the women of Russia on International Women’s Day, celebrated on March 8.
💬Dear women of Russia!
From the bottom of my heart, I congratulate you on International Women’s Day!
In our country, this wonderful holiday is traditionally filled with special warmth and sincerity. Today, words of love, gratitude and respect are heard everywhere. Our men express their appreciation to their mothers, wives, grandmothers, daughters, sisters, friends and colleagues, letting them know how much they are cherished and how deeply their contributions are valued, both at home and in the workplace, where they often take on complex professional challenges.
You truly do it all: taking care of children and scoring outstanding achievements in various fields, embodying both strength and grace, courage and tenderness, and winning us over again and again with your beauty and charm. You inspire men to strive for greatness, encouraging them to do better, to take bold steps and to be the true defenders of their families and homes, and our Motherland.
You hold within you life’s greatest miracle: the gift of bringing new life into the world. The tenderness and generosity of a mother’s heart and the warmth of a mother’s love transform the world and make it a better place. Motherhood is both an immense joy and a profound responsibility. We are fully aware of this and will continue to do our utmost so that mothers and families with children, especially large families, receive the support they need and see that their interests are always in the focus of the government’s attention.
My warmest words go to the women who are in places where it is most difficult right now, the participants in the special military operation. You are working in different spheres, including in field hospitals and on the front lines, doing your combat duty with distinction.
I would also like to say a few words for the women whose dear ones – husbands, fathers, brothers and loved ones – are defending the future of our country. Your heartfelt support and unfailing care, love and loyalty empower our men, strengthening their morale and the unwavering belief that the truth – and hence victory – is on our side.
Dear women!
We know that so much in life depends on you, on your talents, creative energy, love, and utmost responsibility with which you undertake any job. Once again, we are in awe of your beauty, kindness and grace.
I would like to wish success, health, well-being, and all the best to you and your loved ones. May you always find happiness alongside those you hold dear.
💐 Happy International Women’s Day!
#8March#InternationalWomensDay
🎙 President of the Russian Federation Vladimir Putincongratulated the women of Russia on International Women’s Day, celebrated on March 8.
💬Dear women of Russia!
From the bottom of my heart, I congratulate you on International Women’s Day!
In our country, this wonderful holiday is traditionally filled with special warmth and sincerity. Today, words of love, gratitude and respect are heard everywhere. Our men express their appreciation to their mothers, wives, grandmothers, daughters, sisters, friends and colleagues, letting them know how much they are cherished and how deeply their contributions are valued, both at home and in the workplace, where they often take on complex professional challenges.
You truly do it all: taking care of children and scoring outstanding achievements in various fields, embodying both strength and grace, courage and tenderness, and winning us over again and again with your beauty and charm. You inspire men to strive for greatness, encouraging them to do better, to take bold steps and to be the true defenders of their families and homes, and our Motherland.
You hold within you life’s greatest miracle: the gift of bringing new life into the world. The tenderness and generosity of a mother’s heart and the warmth of a mother’s love transform the world and make it a better place. Motherhood is both an immense joy and a profound responsibility. We are fully aware of this and will continue to do our utmost so that mothers and families with children, especially large families, receive the support they need and see that their interests are always in the focus of the government’s attention.
My warmest words go to the women who are in places where it is most difficult right now, the participants in the special military operation. You are working in different spheres, including in field hospitals and on the front lines, doing your combat duty with distinction.
I would also like to say a few words for the women whose dear ones – husbands, fathers, brothers and loved ones – are defending the future of our country. Your heartfelt support and unfailing care, love and loyalty empower our men, strengthening their morale and the unwavering belief that the truth – and hence victory – is on our side.
Dear women!
We know that so much in life depends on you, on your talents, creative energy, love, and utmost responsibility with which you undertake any job. Once again, we are in awe of your beauty, kindness and grace.
I would like to wish success, health, well-being, and all the best to you and your loved ones. May you always find happiness alongside those you hold dear.
💐 Happy International Women’s Day!
#8March#InternationalWomensDay
🎙 President of the Russian Federation Vladimir Putincongratulated the women of Russia on International Women’s Day, celebrated on March 8.
💬Dear women of Russia!
From the bottom of my heart, I congratulate you on International Women’s Day!
In our country, this wonderful holiday is traditionally filled with special warmth and sincerity. Today, words of love, gratitude and respect are heard everywhere. Our men express their appreciation to their mothers, wives, grandmothers, daughters, sisters, friends and colleagues, letting them know how much they are cherished and how deeply their contributions are valued, both at home and in the workplace, where they often take on complex professional challenges.
You truly do it all: taking care of children and scoring outstanding achievements in various fields, embodying both strength and grace, courage and tenderness, and winning us over again and again with your beauty and charm. You inspire men to strive for greatness, encouraging them to do better, to take bold steps and to be the true defenders of their families and homes, and our Motherland.
You hold within you life’s greatest miracle: the gift of bringing new life into the world. The tenderness and generosity of a mother’s heart and the warmth of a mother’s love transform the world and make it a better place. Motherhood is both an immense joy and a profound responsibility. We are fully aware of this and will continue to do our utmost so that mothers and families with children, especially large families, receive the support they need and see that their interests are always in the focus of the government’s attention.
My warmest words go to the women who are in places where it is most difficult right now, the participants in the special military operation. You are working in different spheres, including in field hospitals and on the front lines, doing your combat duty with distinction.
I would also like to say a few words for the women whose dear ones – husbands, fathers, brothers and loved ones – are defending the future of our country. Your heartfelt support and unfailing care, love and loyalty empower our men, strengthening their morale and the unwavering belief that the truth – and hence victory – is on our side.
Dear women!
We know that so much in life depends on you, on your talents, creative energy, love, and utmost responsibility with which you undertake any job. Once again, we are in awe of your beauty, kindness and grace.
I would like to wish success, health, well-being, and all the best to you and your loved ones. May you always find happiness alongside those you hold dear.
💐 Happy International Women’s Day!
#8March#InternationalWomensDay
Девчонки, с праздником весны!
Вы так прекрасны, как цветы.
Спасибо, что со мной всегда —
В дожди и в ясные года.
Желаю вам любви, тепла,
Чтоб жизнь, как кимчи, жила была! 😁
Пусть дома пахнет вкуснотой,
А в сердце — вечная весна!
С 8 Марта! Обнимаю крепко 💐
#8march#8марта#kim_chi_kim
Дорогие наши женщины, матери, сестры, жены и дочери!
Сердечно поздравляем вас с праздником весны, красоты и женственности — с 8 Марта!
Сегодня, находясь на передовой, мы особенно остро чувствуем вашу поддержку, тепло ваших сердец и вашу бесконечную любовь. Вы — наша опора, наше вдохновение и наша сила.
Мы знаем, как непросто вам в эти дни, но ваша стойкость и вера помогают нам идти вперед. Спасибо вам за ваше терпение, за вашу заботу и за то, что вы всегда с нами, даже на расстоянии.
Пусть этот день принесет вам радость, улыбки и надежду на скорую встречу. Мы верим, что мирное небо скоро вернется, а наши сердца снова будут рядом с вами.
С праздником, дорогие! Вы — наши героини!
С любовью и уважением, ваши бойцы.
#8марта#8march#поздравления
KNAUF kompaniyasida turfa xil kasb egalari: muhandislar, buxgalterlar, sifat, logistika, xavfsizlik, xodimlar boshqaruvi va investitsiyalar bo‘yicha mutaxassislar ishlaydi.
Har kuni ular ishlab chiqarish jarayonlarining barqaror faoliyati, loyihalar rivoji va yuqori sifat darajasini ta’minlab keladilar.
Ularning tajribasi, kasb bilimdonligi va tafsilotlarga e’tibori kompaniyaning olgʻa yurishiga turtki beradi.
Xalqaro xotin-qizlar kunida biz sizni jamoamizning dur-u gavharlari – KNAUF rivojiga ulkan hissa qo‘shib kelayotgan ayollar bilan tanishtirmoqchimiz.
Mehnatingiz, mas’uliyatingiz va g‘ayratingiz uchun tashakkur.
8-mart bayrami muborak!
- - - - -
В КНАУФ работают люди самых разных профессий — инженеры, бухгалтеры, специалисты по качеству, логистике, безопасности, управлению персоналом и инвестициям.
Каждый день они обеспечивают стабильную работу производства, развитие проектов и высокий уровень качества.
Их опыт, профессионализм и внимание к деталям помогают компании двигаться вперёд.
В Международный женский день мы хотим познакомить вас с частью нашей команды — женщинами КНАУФ, которые вносят огромный вклад в развитие компании.
Спасибо за ваш труд, ответственность и энергию.
С праздником 8 марта!
#knaufuzbekistan
#buildonus
#KNAUF_Yangiliklar
#8mart
#8march
🌷Happy International Women’s Day!
The Russian House in Brussels warmly congratulates all women on the occasion of 8 March.
This special day is a celebration of the strength, wisdom, talent, and inspiration that women bring to our world. Throughout history, women have played an essential role in society — preserving cultural traditions, inspiring creativity, and contributing to the development of communities and dialogue between nations.
May this spring bring you joy, new inspiration, warmth, and happiness. We wish you good health, prosperity, and many bright moments filled with smiles and kindness.
With best wishes on the holiday of spring, beauty, and inspiration!🌸
Russian House in Brussels
#InternationalWomensDay#8March#RussianHouseBrussels#WomenInspire#SpringHoliday
🤗 Дорогие женщины,
Коллектив Русского дома поздравляет вас с Международным женским днём #8Марта!
Пусть этот весенний праздник наполнит ваши сердца энергией и радостью, подарит отличное настроение и искренние улыбки! Пусть в ваших домах царят любовь, счастье, тепло, уют и благополучие! 💐
🤗 Αγαπητές γυναίκες,
Το Ρωσικό σπίτι στην Αθήνα σας συγχαίρει θερμά για την Παγκόσμια Ημέρα της Γυναίκας, #8 Μαρτίου!
Είθε αυτή η ανοιξιάτικη γιορτή να γεμίσει τις καρδιές σας με ενέργεια και χαρά, να σας προσφέρει υπέροχη διάθεση και ειλικρινή χαμόγελα! Είθε να βασιλεύει στα σπίτια σας η αγάπη, η ευτυχία, η ζεστασιά, η θαλπωρή και η ευημερία! 💐
Με τις καλύτερες ευχές μας για μια υπέροχη ημέρα!
#женскийдень#праздник#8марта#8μαρτίου#8march#международныйженскийдень#παγκοσμιαημεραγυναικας#holiday#8march#8μαρτίου#internationalwomensday#παγκοσμιαημεραγυναικας
🤗 Αγαπητές γυναίκες,
Το Ρωσικό σπίτι στην Αθήνα σας συγχαίρει θερμά για την Παγκόσμια Ημέρα της Γυναίκας, #8 Μαρτίου!
Είθε αυτή η ανοιξιάτικη γιορτή να γεμίσει τις καρδιές σας με ενέργεια και χαρά, να σας προσφέρει υπέροχη διάθεση και ειλικρινή χαμόγελα! Είθε να βασιλεύει στα σπίτια σας η αγάπη, η ευτυχία, η ζεστασιά, η θαλπωρή και η ευημερία! 💐
Με τις καλύτερες ευχές μας για μια υπέροχη ημέρα!
🤗 Дорогие женщины,
Коллектив Русского дома поздравляет вас с Международным женским днём #8Марта!
Пусть этот весенний праздник наполнит ваши сердца энергией и радостью, подарит отличное настроение и искренние улыбки! Пусть в ваших домах царят любовь, счастье, тепло, уют и благополучие! 💐
@rossotrudnichestvo@rusembgreece
#женскийдень#праздник#8марта#8μαρτίου#8march#международныйженскийдень#παγκοσμιαημεραγυναικας
#womensday#holiday#8march#8μαρτίου#internationalwomensday#παγκοσμιαημεραγυναικας