pub struct PriorityLock<T> { /* private fields */ }Expand description
A lock that allows sharing data between two interrupts at different priorities.
This is a general spinlock-like implementation that works even on architectures without compare-and-swap instructions. This is accomplished by making use of Peterson’s Algorithm.
§Drawbacks
Being a general architecture-independent implementation means that it also comes with some drawbacks due to not knowing anything about the target platform:
- It is limited to 2 parties sharing data. Peterson’s Algorithm requires storage proportional to the number of parties competing for exclusive access. With const generics it might be possible to make this a compile-time parameter instead.
- Locking from an interrupt can fail irrecoverably. This is a fundamental limitation of trying to ensure exclusive access via blocking mutexes in the presence of interrupts, and would also occur when using any other generic solution (like a “real” spinlock). User code must handle a failure to acquire a resource in an interrupt handler gracefully.
§Alternatives
If the drawbacks listed above are unacceptable (which is not unlikely), consider using one of these alternatives for sharing data between interrupts:
- Lock-free datastructures such as those provided by heapless.
- Atomics and read-modify-write operations from
core::sync::atomic(if your target supports them). - A Mutex implementation that turns off interrupts (when targeting a single-core MCU).
- A hardware-provided Mutex peripheral (when targeting a multi-core MCU).
- The Real-Time For the Masses framework.
Implementations§
Source§impl<T> PriorityLock<T>
impl<T> PriorityLock<T>
Sourcepub const fn new(data: T) -> Self
pub const fn new(data: T) -> Self
Creates a new lock protecting data.
If data consists of zeroes, the resulting PriorityLock will also be zero-initialized
and can be placed in .bss by the compiler.
Sourcepub fn split<'a>(
&'a mut self,
) -> (LockHalf<'a, T, PLow>, LockHalf<'a, T, PHigh>)
pub fn split<'a>( &'a mut self, ) -> (LockHalf<'a, T, PLow>, LockHalf<'a, T, PHigh>)
Splits this lock into its low- and high-priority halfs.
The low-priority half provides a lock method for acquiring the lock, and is meant to be
used from a lower-priority context than the high-priority half (eg. a low-priority
interrupt or the application’s idle loop). The high-priority half provides a try_lock
method for acquiring the lock, which may fail when preempting code holding the low-priority
half of the lock.