Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Sen. Bernie Sanders (D-VT) got animated during an interview with CNN's Kaitlan Collins on Tuesday night over President Donald Trump's latest threat to withhold federal funding from New York City.
Sanders joined Collins to discuss the looming government shutdown. He expressed concern that the Trump administration could use the shutdown to continue advancing its authoritarian agenda, citing previous examples like firing workers that "they don't like" from the Veterans Administration and making significant cuts to Medicaid.
"I'll give you another example, as I'm sure you've heard of it," Sanders told Collins. "I think it was yesterday. Trump says, 'Well, if Mr. [Zohran] Mamdani becomes the mayor of New York City, then I'm going to cut funding from New York City.'"
#Trump#Sanders
👂More on Trump's Ear ⚠️
✊ As Senator Bernie Sanders and Representative Alexandria Ocasio-Cortez joined Zohran Mamdani on Sunday at Forest Hills Stadium, a bigger test for the left may still lie ahead. 🌆📣
#NY#Mamdani#Sanders
👂More on Trump's Ear
⚠️
🇺🇸 Spinto da giovani e ispanici, Bernie #Sanders ha stravinto i #caucus del #Nevada.
➡️ Tutti i risultati e l'analisi del voto:
https://www.youtrend.it/2020/02/24/come-bernie-sanders-ha-vinto-in-nevada/
#USA#Primarie#D
Secondo il WP, gli stretti collaboratori di Bernie #Sanders (#VPP|Sinistra) riferiscono che il Senatore sarebbe pronto a candidarsi alle primarie democratiche nel 2024, qualora il presidente in carica Joe #Biden rifiutasse di correre per la rielezione.
@UltimoraPolitics
#USA#Ucraina#Israele#Taiwan
Il #Senate ha approvato, con 67 voti favorevoli e 27 contrari, la chiusura dell’accordo per la fornitura di aiuti per un ammontare pari a 95 miliardi di dollari a Ucraina, Israele e Taiwan.
Anche 18 senatori repubblicani hanno votato a favore dell’accordo, mentre Bernie #Sanders (#D|Centro-sinistra) è stato l’unico dem ad opporsi alla fornitura di aiuti a tali nazioni.
@OsservatorioEsteri
Attualmente, Joe #Biden ha un vantaggio larghissimo in #Mississippi e #Missouri, un vantaggio ampio in #Michigan e un vantaggio molto ristretto in #NorthDakota.
Bernie #Sanders invece ha un vantaggio ristretto in #Idaho, #Washington e fra i #DemocratsAbroad