Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
On May 27, 2025, an official meeting was held at the Somon Air office between the airline's management and representatives of Xinjiang Airport Group Co., Ltd.
During the meeting, the parties discussed the current state of the international aviation services market, including between Xinjiang and the Central Asian countries. The purpose of the Chinese delegation’s visit was to explore prospects for mutually beneficial cooperation and to engage in in-depth dialogue on the development of air communication and the expansion of the route network between cities in the Republic of Tajikistan and cities in the Xinjiang Uyghur Autonomous Region of the People’s Republic of China.
Xinjiang Airport Group Co., Ltd was represented at the meeting by General Manager of Xinjiang Airport Group Lu Huibin and Director of Marketing Committee Zhang Jun.
#somonair#xinjiang#aviation
👏Такла-Макан: от «Моря Смерти» к зеленому оазису
🔹Пустыня Такла-Макан, когда-то известная как грозное «Море Смерти», веками отпугивала путешественников. Но всего за последний год в уезде Юйтянь (Синьцзян-Уйгурский автономный район, Китай) были преобразованы огромные участки бесплодных земель на окраинах этой пустыни.
🌳 Хотите увидеть, как пески медленно, но верно превращаются в процветающий зеленый оазис? Тогда смотрите видео! 🤩
#explorexinjiang#Синьцзян#Xinjiang#TaklimakanDesert
China uses one official time zone: China Standard Time (CST), 8 hours ahead of UTC, called Beijing Time. In Xinjiang, many Uyghurs use Xinjiang Time, 2 hours behind CST. China does not change clocks for Daylight Saving Time.
To see the current time check [here]
@googlefactss⏰🇨🇳
#China#TimeZone#CST#Xinjiang#BeijingTime#funfact
As Europe deepens its economic ties with China, its willingness to confront Beijing over human rights abuses appears to be waning. A recent article highlights how European nations are prioritizing trade and diplomacy, even as concerns about rights violations in Xinjiang and Tibet persist. Critics warn that this compromises Europe's commitment to human rights and raises questions about its moral leadership on the global stage.
#EuropeChinaRelations#HumanRights#Xinjiang#Tibet#GlobalDiplomacy#TheEconomist
隨著歐洲加強與中國的經濟聯繫,對北京人權問題的關注似乎日漸減弱。一篇最新文章指出,儘管新疆和西藏的權益問題仍存,歐洲各國卻更注重貿易和外交關係。有批評者警告,這將削弱歐洲對人權的承諾,並對其全球道德領導力提出質疑。
#歐中關係#人權問題#新疆#西藏#全球外交#經濟學人
https://www.economist.com/international/2025/03/25/europe-will-have-to-zip-its-lip-over-chinas-abuses
#Beijing_Review🇨🇳📕[PDF]⬇️
2 #October2025
#Weekly_Magazines
For learning, for free(dom).
@backupofmagazines
In this issue , the spotlight shines on #Xinjiang 70, celebrating seven decades of transformation in the autonomous region—from economic health to cultural heritage. Global topics include #PalestineRecognition, evolving #ChinaUS relations, and the healing potential of dialogue via the #XiangshanForum. Special features explore #RuralRevitalization and tech-driven change in Qingdao and Fujian, as #ScienceInnovation takes center stage. From the vibrant Grand Bazaar to a Somali expat’s vision, this issue captures both regional pride and global dialogue. #BeijingReview#CulturalDiversity#BeltAndRoad#EducationMatters#ChinaPerspective