Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Обонятельные луковицы мыши в наноскопическом разрешении. За этой видяшкой примерно петабайт (><) данных.
#expansion#microscopy
Экспансионная микроскопия позволяет добиться фантастического разрешения, но у неё есть, конечно проблемы. Одна из них неочевидная, пока об этом не задумываешься. Но логичная.
Образец становится большим. Иногда большим чем рабочая дистанция объективов, соответственно заметная часть нашего великолепного образца с нанотдетализацией остаётся за кадром.
Что делать если все таки хочется рассмотреть объект целиком?
Авторы статьи Mesoscale volumetric fluorescence imaging at nanoscale resolution by photochemical sectioning предложили интересное решение. Они сделали гель для экспансии такого состава, который разрушается под действием УФ, что позволило им нарезать (лазером) гель в процессе сьемки. Фактически они сделали оптический FIB (метод из электронной микроскопии, где образец нарезают пучком ионов).
В комментах видео с подробностями из твиттера автора статьи Ruixuan Gao
In the latest episode of DWF Chats, we hosted:
🔹Micky Watkins (Founder and CEO, World Mobile Group)
🔹Zachary Vann (Head of Token, World Mobile Token)
Hear more about WMT's scalability and their #expansion roadmap, the utility of WMT token and how you can get involved in WMT #community✨
Full interview here.
//
About:
▫World Mobile Token aims to build a #decentralised telecommunication network to deliver affordable, quality Internet access to the unconnected.
Visit http://worldmobiletoken.com to find out more.
🪐 The end of the universe is a cosmic puzzle with several real scenarios proposed by scientists, each based on clues from galaxies like Messier 87 and ancient light observed by telescopes. One idea is the "Big Bounce," where the universe’s expansion might someday reverse due to gravity, causing everything—including stars such as Betelgeuse and black holes like Sagittarius A*—to collapse back into an ultra-dense state, possibly leading to another cosmic cycle. Unlike the "Big Freeze" or "Big Rip," the "Big Bounce" is still debated, but it shows how the fate of the universe could depend on the balance between gravity and mysterious forces such as dark energy. ✨
#universe⚡#cosmology⚡#expansion⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Over billions of years, the expansion of the universe—measured by observing distant galaxies like Messier 87—will stretch space so much that the light from other galaxies will eventually fade from view. Long after stars like our Sun burn out, only the dead remnants of stars and black holes will remain, and as cosmic expansion continues, even these may become isolated in a cold, dark universe, ending with silent emptiness. ✨
#universe⚡#fate⚡#expansion⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The Sun, along with all stars in the Milky Way, will eventually run out of fuel and end as a white dwarf—a small, cool stellar remnant. Over trillions of years, even white dwarfs like the one in Messier 4 will cool and fade to black, leaving the universe filled with cold, dark remnants, while galaxies such as Andromeda drift farther apart as cosmic expansion continues. ✨
#universe⚡#fate⚡#expansion⚡#stars⚡#nasa⚡#galaxy⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 One of the great cosmic mysteries is how the universe will end, and scientists look to real clues from galaxies like Andromeda and stars such as the Sun to guide their ideas. Some theories suggest the universe might continue expanding forever, causing galaxies to drift so far apart that even light from Andromeda will never reach us again, while others consider whether the universe’s own gravity could eventually pull everything—stars, planets, and even black holes—back together in a colossal collapse, erasing all known cosmic structures. ✨
#universe⚡#fate⚡#expansion⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
寒蝉鸣泣之时 虚崩篇
▎介绍
■■ <注意>.
不提供任何担保。 请自行承担使用风险。
日暮之夜 "的版权归 Circle 07th_Expansion 所有。
日暮之夜 "的版权归 Circle 07th_Expansion 所有。
Mui Mui Mui 制作的文库。 使用 Mui Mui 制作的文库 (
http://d.hatena.ne.jp/eiji8pou/20050914/1126709682)。
该库的版权归 Mui Mui 所有。 资料库版权归 Mui Mui 所有。
世界设定。
节日音乐版和碎片旋转后的世界。
如果没有玩过林松里版,故事可能会显得跳跃。
古特家族的设定与主家族有明显不同。
故事的主角是敬岚和敬石。 (故事是关于敬岚和敬志的)。
有仇恨! 注意事项
▎获取
PC仓库
▎标签
系统:#PC
类型:#galgame#NSWF#汉化
系列:#寒蝉鸣泣之时
出版:#Expansion