Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#AFP journalist blocked from flying to #Ethiopia's #Tigray region
An AFP journalist was on Thursday barred from boarding a flight to Tigray in northern Ethiopia, where renewed tensions in recent months have raised fears of fresh conflict.
An accredited AFP reporter based in Addis Abeba was blocked from boarding a flight to Shire in Tigray because he did not have authorization from the Ethiopian Ministry of Foreign Affairs.
https://addisstandard.com/?p=55247
Dopo il quotidiano inglese #FinancialTimes oggi ne parla anche l'agenzia francese #AFP: "Le truppe turche per il salvataggio delle persone possono essere impiegate a #Gaza per trovare i corpi degli ostaggi israeliani sotto le macerie".
#Drone strike at #Sudan's border with #Ethiopia kills one: authorities
A drone attack blamed on paramilitary forces killed one person Thursday in the Sudanese town of Kurmuk, on the border with Ethiopia, authorities said.
"One person was killed, eight injured and 16 houses destroyed," a government source told #AFP by phone from #Kurmuk, a border town controlled by the army in Sudan's Blue Nile state.
In a statement, Kurmuk governor Abdelaty Mohamed al-Fiky blamed the strike on the paramilitary Rapid Support Forces (#RSF), at war with the army since April 2023, and their allies, a faction of the Sudan People's Liberation Movement-N orth (SPLM-N). Blue Nile state is the latest front in nearly three years of devastating war, now being fought mainly with deadly drone strikes. The fighting has left tens of thousands dead and around 11 million displaced, creating the world's largest hunger and displacement crises.
https://www.facebook.com/share/18JNprLucH/
News: AI-generated war narratives fuel #Ethiopia–Eritrea tensions online: report
Artificial intelligence (#AI) generated images and videos portraying a hypothetical #Ethiopian military takeover of #Eritrea’s strategic port of #Assab are increasingly shaping online narratives and inflaming tensions between the two countries, according to a report by #AFP.
One of the most prominent creators, 24-year-old Ethiopian law graduate Eliyas Kebede Zemedkun, who has more than 87,000 Facebook followers, told AFP he has spent much of 2026 producing AI-generated content depicting Ethiopia occupying Assab to promote what he described as “Ethiopia’s national narrative.” “I am also motivated to use AI-generated content to challenge narratives that try to downgrade the national army through different demoralizing tactics,” he said, adding that he uses free platforms such as #ChatGPT and #Gemini alongside editing software to create the material.
Read more: https://addisstandard.com/?p=56283