Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🌍 In 1815, Indonesia’s Mount Tambora erupted so violently that it triggered “the year without a summer.” Global temperatures dropped, causing crop failures and food shortages across continents. ✨
#disaster⚡#volcano⚡#climate⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 In 2015, Chile’s Calbuco volcano erupted after 43 years of silence, blasting ash over 15 kilometers high. Its sudden activity disrupted air travel and blanketed towns in thick volcanic dust. ✨
#volcano⚡#disaster⚡#eruption⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In 2023, Cyclone Freddy became the longest-lasting tropical cyclone ever recorded, traveling over 12,000 kilometers and affecting countries from Madagascar to Mozambique with powerful winds and rain. ✨
#cyclone⚡#disaster⚡#weather⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 In 2023, Cyclone Mocha became one of the strongest storms ever recorded in the North Indian Ocean, with winds over 250 km/h, causing severe flooding and reshaping coastal landscapes. ✨
#disaster⚡#cyclone⚡#flooding⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In 2023, Cyclone Biparjoy spun over the Arabian Sea for nearly two weeks—a rare “very severe cyclonic storm” to last so long in this region, with winds impacting coasts over 1,000 kilometers apart. ✨
#cyclone⚡#disaster⚡#winds⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The 1811–1812 New Madrid earthquakes in the central United States were so powerful they briefly made the Mississippi River flow backward, reshaping the landscape far from any plate boundary. ✨
#disaster⚡#earthquake⚡#river⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
On 26 April 1986, the Chernobyl disaster occurred at the Chernobyl Nuclear Power Plant in the Soviet Union (now Ukraine). During a safety test on Reactor 4, operators lost control of the reactor. This caused a powerful explosion and fire that destroyed the reactor and released large amounts of radioactive material into the atmosphere. It is considered the worst nuclear accident in history. The nearby city of Pripyat was evacuated after the explosion. The area is mostly uninhabited, but a small number of people still live or work there.
☢️🏭🌍
[Read more 1]
[Read more 2]
@googlefactss
#Chernobyl#NuclearAccident#History#Ukraine#Disaster
If you have ideas or feedback contact us:
@Googlefactss_Feedback_bot