Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Stract is an open source search engine where the user has the ability to see exactly what is going on and customize almost everything about their search results. It's a search engine made for hackers and tinkerers just like ourselves. No more searches where some of the terms in the query arent used, and the engine tries to guess what you really meant. You get what you search for.
https://stract.com
https://github.com/StractOrg/stract
#Web#Search#SearchEngine
#FLOSS
SimpleX Chat: private and secure cross platform messenger without any user IDs (not even random)
:~ E2E-encrypted messages with markdown and editing
:~ E2E-encrypted images and files
:~ Decentralized secret groups — only users know they exist
:~ E2E-encrypted voice messages
:~ Disappearing messages
:~ E2E-encrypted audio and video calls
:~ Portable encrypted database — move your profile to another device
:~Incognito mode —
unique to SimpleX Chat
Website : https://simplex.chat/
SimpleX Chat (SimpleX Chat - e2e encrypted messenger without any user IDs - private by design!)
https://f-droid.org/packages/chat.simplex.app/
Quick start – https://simplex.chat/docs/guide/readme.html
#SimpleXchat#security#privacy#encryption#E2EE
#FLOSS
NAPS2 - Scan #documents to PDF and more – https://www.naps2.com/
NAPS2 is free and open source scanning software for Windows, Mac and Linux.
Easily scan with devices from Canon, Brother, HP, Epson, Fujitsu, and more. Then save to #PDF, #TIFF, #JPEG, or #PNG with a single click.
#Scan#Floss
#cplusplus#apple_silicon#bsd#c_plus_plus#cmake#floss#game#gplv2#json#linux#lua#macos_app#python#strategy#windows
Widelands is a free, open-source real-time strategy game like Settlers II, where you lead a small clan to build roads, gather resources like wood and gold, manage four unique tribes, trade, or fight in single-player campaigns and multiplayer. Download it easily for Windows, Mac, or Linux, or compile from source with simple scripts and tools like CMake on various systems. This lets you enjoy deep, replayable empire-building fun at no cost, anytime with friends or AI.
https://github.com/widelands/widelands