Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🇧🇩#Bangladesh – Il National Citizen Party (#NCP), fondato dagli studenti Gen Z che hanno portato alla caduta dell’ex premier Sheikh #Hasina, si coalizzerà con i partiti islamisti in vista delle elezioni di febbraio. Diversi dirigenti e candidati riformisti si sono dimessi in seguito alla decisione che potrebbe portare il clero islamico al governo.
@UltimoraPolitics24
News: Former #Sudan PM Hamdok says Islamist factions major obstacle to ending war
Abdalla Hamdok, Former Sudanese Prime Minister and head of the Somoud civilian coalition, has said Islamist factions linked to Sudan’s former ruling party are among the main obstacles to ending the country’s nearly three-year civil war, according to a report by Abu Dhabi-based newspaper The National.
Speaking to the newspaper on the sidelines of the 39th African Union summit in #Addis_Abeba, Hamdok said Islamist groups and the National Congress Party (#NCP) — the political party of ousted president Omar Al Bashir — remains key actors resisting peace initiatives and efforts to reach a broader national consensus.
He also criticized Sudan’s army chief, Gen Abdel Fattah #Al_Burhan, for insisting on a military solution to defeat the rival Rapid Support Forces (#RSF). Al Burhan has publicly ruled out peace....
https://web.facebook.com/AddisstandardEng/posts/pfbid02qycixQfoRJLo5F9EWtxgsymfNbxMqUa9D4Qquz6X3DjfUBUFxig1b3xTGb3MzEHHl
🇧🇩#Bangladesh – Oggi oltre 120 milioni di cittadini sono stati chiamati alle urne per rinnovare i 350 seggi del Parlamento, le prime elezioni dopo la deposizione della premier Sheikh #Hasina e la messa al bando della Lega Awami. Si sono sfidati il Partito Nazionalista Bengalese (#BNP) di Tarique #Rahman (rientrato dall’esilio a Londra dopo 17 anni), di centro-destra, per la liberalizzazione dell’economia, vicino alla classe media e all’esercito, e la coalizione guidata dal partito islamista Jamaat-e-Islami (#Jamaat) di Shafiqur #Rahman, che punta a introdurre la sharia nel Paese. La coalizione include il Partito Nazionale dei Cittadini (#NCP), fondato dai leader delle proteste studentesche, ma l’alleanza con gli islamisti è stata fortemente contestata da donne, laici e minoranza indù che avevano sostenuto le proteste. Risultati nelle prossime ore.
@UltimoraPolitics24