Telegram Group & Telegram Channel
#prog #rust #rustasync #article

На этот раз — целая серия статей от Cliff L. Biffle. Все из них прямо или косвенно связаны с lilos — подходящая для встраиваемых систем операционная система реального времени, которая использует растовый async для запуска тасок (= приложений в этой OS) и потребляет очень мало ресурсов как в долговременной памяти, так и в оперативной:

This is a wee operating system written to support the async style of programming in Rust on microcontrollers. It fits in about 2 kiB of Flash and uses about 20 bytes of RAM (before your tasks are added). In that space, you get a full async runtime with multiple tasks, support for complex concurrency via join and select, and a lot of convenient but simple APIs.

lilos has been deployed in real embedded systems since 2019, running continuously. I've built about a dozen systems around it of varying complexity, on half a dozen varieties of microcontroller. It works pretty okay! Perhaps you will find it useful too.

Первая статья, которую я хочу затронуть — это How to think about `async`/`await` in Rust. В ней рассказывается о принципиальном отличии async fn от обычных функций — о том, что async fn суть машина состояний и потому в случае асинхронных функций контроль над исполнением кода имеет вызывающая сторона — а также немного о том, в какие практические следствия это вытекает.

Вторая статья: Composing concurrency in drivers (An example of why I like async for embedded). На примере наброска I2C-драйвера автор показывает, как можно добавить в код драйвера обработку ошибок и прерываний, не внося изменений в бизнес-логику протокола. Эта возможность весьма существенно полагается на особенности реализации async в Rust. Если быть более конкретным, итоговый код полагается на futures::select_biased!.

Как несложно догадаться, для корректной работы подобного кода исполняемые футуры должны быть cancel safe. Как сказано в документации к tokio::select!:

Cancellation safety can be defined in the following way: If you have a future that has not yet completed, then it must be a no-op to drop that future and recreate it. This definition is motivated by the situation where a select! is used in a loop. Without this guarantee, you would lose your progress when another branch completes and you restart the select! by going around the loop.

И cancellation safety обладает рядом крайне неприятных свойств:

* Она (или её отсутствие, что немаловажно) редко задокументирована.
* Cancellation unsafety заразительна: если футура не является cancel safe, то поверх неё невозможно сделать cancel safe обёртку.
* Cancellation safety (в отличие от weak exception safety) не композируется: можно взять два куска асинхронного кода, каждый из которых по отдельности cancel safe, и совместить их так, что получится cancel unsafe код.
* Так как cancellation safety является довольно сложным семантическим свойством (и, как справедливо замечают в документации tokio, cancel unsafe код — это не всегда что-то плохое), cancellation safety никак не отслеживается компилятором.

(конкретно последний пункт можно было бы, в теории, починить, используя линейные типы — а не афинные, как сейчас в Rust — но, как писал лодочник, впихнуть их в уже существующий язык с широкой экосистемой весьма сложно)

Имеющуюся плачевную ситуацию можно до какой-то степени улучшить, предоставив набор документированных cancel safe примитивных операций. И вот тут lilos заметно отличается от прочих асинк-экосистем. В статье с провокационным названием Mutex without lock, Queue without push: cancel safety in lilos автор рассказывает, как он смог сделать API в lilos cancel safe, причём в более строгом смысле, чем обычно. Именно, автор вводит несколько уровней cancellaton safety:



group-telegram.com/dereference_pointer_there/6762
Create:
Last Update:

#prog #rust #rustasync #article

На этот раз — целая серия статей от Cliff L. Biffle. Все из них прямо или косвенно связаны с lilos — подходящая для встраиваемых систем операционная система реального времени, которая использует растовый async для запуска тасок (= приложений в этой OS) и потребляет очень мало ресурсов как в долговременной памяти, так и в оперативной:

This is a wee operating system written to support the async style of programming in Rust on microcontrollers. It fits in about 2 kiB of Flash and uses about 20 bytes of RAM (before your tasks are added). In that space, you get a full async runtime with multiple tasks, support for complex concurrency via join and select, and a lot of convenient but simple APIs.

lilos has been deployed in real embedded systems since 2019, running continuously. I've built about a dozen systems around it of varying complexity, on half a dozen varieties of microcontroller. It works pretty okay! Perhaps you will find it useful too.

Первая статья, которую я хочу затронуть — это How to think about `async`/`await` in Rust. В ней рассказывается о принципиальном отличии async fn от обычных функций — о том, что async fn суть машина состояний и потому в случае асинхронных функций контроль над исполнением кода имеет вызывающая сторона — а также немного о том, в какие практические следствия это вытекает.

Вторая статья: Composing concurrency in drivers (An example of why I like async for embedded). На примере наброска I2C-драйвера автор показывает, как можно добавить в код драйвера обработку ошибок и прерываний, не внося изменений в бизнес-логику протокола. Эта возможность весьма существенно полагается на особенности реализации async в Rust. Если быть более конкретным, итоговый код полагается на futures::select_biased!.

Как несложно догадаться, для корректной работы подобного кода исполняемые футуры должны быть cancel safe. Как сказано в документации к tokio::select!:

Cancellation safety can be defined in the following way: If you have a future that has not yet completed, then it must be a no-op to drop that future and recreate it. This definition is motivated by the situation where a select! is used in a loop. Without this guarantee, you would lose your progress when another branch completes and you restart the select! by going around the loop.

И cancellation safety обладает рядом крайне неприятных свойств:

* Она (или её отсутствие, что немаловажно) редко задокументирована.
* Cancellation unsafety заразительна: если футура не является cancel safe, то поверх неё невозможно сделать cancel safe обёртку.
* Cancellation safety (в отличие от weak exception safety) не композируется: можно взять два куска асинхронного кода, каждый из которых по отдельности cancel safe, и совместить их так, что получится cancel unsafe код.
* Так как cancellation safety является довольно сложным семантическим свойством (и, как справедливо замечают в документации tokio, cancel unsafe код — это не всегда что-то плохое), cancellation safety никак не отслеживается компилятором.

(конкретно последний пункт можно было бы, в теории, починить, используя линейные типы — а не афинные, как сейчас в Rust — но, как писал лодочник, впихнуть их в уже существующий язык с широкой экосистемой весьма сложно)

Имеющуюся плачевную ситуацию можно до какой-то степени улучшить, предоставив набор документированных cancel safe примитивных операций. И вот тут lilos заметно отличается от прочих асинк-экосистем. В статье с провокационным названием Mutex without lock, Queue without push: cancel safety in lilos автор рассказывает, как он смог сделать API в lilos cancel safe, причём в более строгом смысле, чем обычно. Именно, автор вводит несколько уровней cancellaton safety:

BY Блог*




Share with your friend now:
group-telegram.com/dereference_pointer_there/6762

View MORE
Open in Telegram


Telegram | DID YOU KNOW?

Date: |

As such, the SC would like to remind investors to always exercise caution when evaluating investment opportunities, especially those promising unrealistically high returns with little or no risk. Investors should also never deposit money into someone’s personal bank account if instructed. What distinguishes the app from competitors is its use of what's known as channels: Public or private feeds of photos and videos that can be set up by one person or an organization. The channels have become popular with on-the-ground journalists, aid workers and Ukrainian President Volodymyr Zelenskyy, who broadcasts on a Telegram channel. The channels can be followed by an unlimited number of people. Unlike Facebook, Twitter and other popular social networks, there is no advertising on Telegram and the flow of information is not driven by an algorithm. Telegram users are able to send files of any type up to 2GB each and access them from any device, with no limit on cloud storage, which has made downloading files more popular on the platform. "We're seeing really dramatic moves, and it's all really tied to Ukraine right now, and in a secondary way, in terms of interest rates," Octavio Marenzi, CEO of Opimas, told Yahoo Finance Live on Thursday. "This war in Ukraine is going to give the Fed the ammunition, the cover that it needs, to not raise interest rates too quickly. And I think Jay Powell is a very tepid sort of inflation fighter and he's not going to do as much as he needs to do to get that under control. And this seems like an excuse to kick the can further down the road still and not do too much too soon." "Someone posing as a Ukrainian citizen just joins the chat and starts spreading misinformation, or gathers data, like the location of shelters," Tsekhanovska said, noting how false messages have urged Ukrainians to turn off their phones at a specific time of night, citing cybersafety.
from us


Telegram Блог*
FROM American