Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Gatto Channel: June Events Calendar
#calendar#events
Gatto | Official Channel (18+) has released a calendar of regular events for June. Collaborations, raffles, and secret events are not listed, requiring subscribers to stay tuned for further announcements.
Source: link
@tonlines
In 46 BC, Julius Caesar added 90 extra days to the year, making it 445 days long. This was done to fix the calendar’s drift from the solar year. The previous calendar was out of sync with the seasons. Caesar introduced the Julian calendar, which included leap years every four years to keep the calendar aligned with the sun.
📅🔧
[Read more]
@googlefactss
#History#Calendar#LeapYear
🌍 Samoa famously skipped December 30, 2011, to switch from the eastern to the western side of the International Date Line. This move aligned its calendar with Australia and New Zealand. ✨
#Samoa⚡#dateline⚡#calendar⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
📅 Calendar Stickers 📅
https://telegram.me/addstickers/Calendar2016
#Calendar#Useful#Hacks
🛠 It could be useful (or even some sort of a lifehack) for users.
Fokus
To Do app tailored specifically for #students
Fokus is an open source application that combines a #todo list and a #calendar that can help you manage your #school related #work and #events in one place. It's fast and beautiful yet simple design that can help you focus on what matters most.
Features:
• Get reminded when a task is nearing its due
• Get reminded about incoming events
• Add attachments to your tasks
• Persistent notifications for important tasks or events
• No ads or any tracking
• Open Source Code
• On-Device Database
Download: https://github.com/icabetong/fokus-android/releases/
https://github.com/icabetong/fokus-android
@foss_Android