Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Croc
Easily and securely send things from one computer to another
Features
- allows any two computers to transfer data (using a relay)
- provides end-to-end encryption (using PAKE)
- enables easy cross-platform transfers (Windows, Linux, Mac, Android)
- allows multiple file transfers
- local server or port-forwarding not needed
- ipv6-first with ipv4 fallback
https://github.com/schollz/croc
https://f-droid.org/en/packages/com.github.howeyc.crocgui/
📡@NoGoolag📡@Libreware
#croc#transfer#send#share
Alt-sendme — send files and folders to anywhere in the world without storing them in the cloud — any size, any format, without accounts and restrictions.
A free file transfer tool with open source code, using the capabilities of an advanced peer-to-peer network, allowing you to transfer files directly without storing them on cloud servers.
@github
#P2P#FileTransfer#share#send#transfer
@etlgr_bot
Qué puede hacer este bot?
Obtén una dirección de correo para cualquier Chat de Telegram (grupo o usuario).
Enviar y recibir correos.
Idioma: Inglés
(visto en @BotsGram_cu)
#send, #mail, #email, #address, #welcome
@Shekelbot
Qué puede hacer este bot?
ShekelBot le ayudará a contar su dinero. Úselo, cuando le das dinero a alguien, o comparte compras.
Idioma: Inglés
(visto en @BotsGram_cu)
#money, #track, #send, #receive, #friends, #debt
@posttobot
Qué puede hacer este bot?
Este bot le ayuda a enviar un mensaje a alguien en Telegram Messenger sin usar Telegram a través de este Bot conectado con una aplicación web.
Idioma: Inglés, Ruso
(visto en @BotsGram_cu)
#web, #pc, #remote, #telegram, #message, #text, #send, #post, #bot, #dictionary
@DebtsTrackerBot
Qué puede hacer este bot?
Este bot realiza un seguimiento de sus deudas y envía recordatorios a usted y a los deudores por Telegram y SMS.
Idioma: Español, Inglés, Ruso, Italiano
(visto en @BotsGram_cu)
#friend, #money, #track, #debt, #send, #receive, #issue, #website, #request