当值在启动时只写入一次然后只能读取时,嵌入式Rust中的Mutex是否有轻量级替代方案?

根据Rust Embedded Book about concurrency,在上下文之间共享某些数据的更好方法之一是使用带有引用单元的互斥锁。我了解它们如何工作以及为什么这样做是必要的。但是在某些情况下,间接费用似乎很多。

cortex_m箱子的互斥体以这种方式工作:

cortex_m::interrupt::free(|cs| {
    let my_value = my_mutex.borrow(cs).borrow();
    // Do something with the value
});

互斥锁需要cs(CriticalSection)令牌才能访问。在关键部分,不会发生中断,因此我们知道我们是唯一可以更改和读取值的中断。效果很好。

但是,我现在所处的场景将变量写入一次以进行初始化(在运行时),然后始终将其视为只读值。就我而言,这是MCU的时钟速度。这不能是编译时常量。为什么要从深度睡眠中唤醒的示例:根据硬件的状态,可以选择使用较低的时钟速度来节省一些能量。因此,在启动(或者唤醒所有RAM都消失了)时,每次都可以选择不同的时钟速度。

如果我只是想读取该值,那么遍历整个关键部分的设置似乎很浪费。如果可以再次更改此变量,则是必须的。但事实并非如此。它只会被读取。

是否有更好的方式来读取共享变量且开销较小,并且不使用不安全的Rust?

qq579694 回答:当值在启动时只写入一次然后只能读取时,嵌入式Rust中的Mutex是否有轻量级替代方案?

借助一些评论,我想到了这一点:

use core::cell::UnsafeCell;
use core::sync::atomic::{AtomicBool,Ordering};

/// A cell that can be written to once. After that,the cell is readonly and will panic if written to again.
/// Getting the value will panic if it has not already been set. Try 'try_get(_ref)' to see if it has already been set.
///
/// The cell can be used in embedded environments where a variable is initialized once,but later only written to.
/// This can be used in interrupts as well as it implements Sync.
///
/// Usage:
/// ```rust
/// static MY_VAR: DynamicReadOnlyCell<u32> = DynamicReadOnlyCell::new();
///
/// fn main() {
///     initialize();
///     calculate();
/// }
///
/// fn initialize() {
///     // ...
///     MY_VAR.set(42);
///     // ...
/// }
///
/// fn calculate() {
///     let my_var = MY_VAR.get(); // Will be 42
///     // ...
/// }
/// ```
pub struct DynamicReadOnlyCell<T: Sized> {
    data: UnsafeCell<Option<T>>,is_populated: AtomicBool,}

impl<T: Sized> DynamicReadOnlyCell<T> {
    /// Creates a new unpopulated cell
    pub const fn new() -> Self {
        DynamicReadOnlyCell {
            data: UnsafeCell::new(None),is_populated: AtomicBool::new(false),}
    }
    /// Creates a new cell that is already populated
    pub const fn from(data: T) -> Self {
        DynamicReadOnlyCell {
            data: UnsafeCell::new(Some(data)),is_populated: AtomicBool::new(true),}
    }

    /// Populates the cell with data.
    /// Panics if the cell is already populated.
    pub fn set(&self,data: T) {
        cortex_m::interrupt::free(|_| {
            if self.is_populated.load(Ordering::Acquire) {
                panic!("Trying to set when the cell is already populated");
            }
            unsafe {
                *self.data.get() = Some(data);
            }

            self.is_populated.store(true,Ordering::Release);
        });
    }

    /// Gets a reference to the data from the cell.
    /// Panics if the cell is not yet populated.
    #[inline(always)]
    pub fn get_ref(&self) -> &T {
        if let Some(data) = self.try_get_ref() {
            data
        } else {
            panic!("Trying to get when the cell hasn't been populated yet");
        }
    }

    /// Gets a reference to the data from the cell.
    /// Returns Some(T) if the cell is populated.
    /// Returns None if the cell is not populated.
    #[inline(always)]
    pub fn try_get_ref(&self) -> Option<&T> {
        if !self.is_populated.load(Ordering::Acquire) {
            None
        } else {
            Some(unsafe { self.data.get().as_ref().unwrap().as_ref().unwrap() })
        }
    }
}

impl<T: Sized + Copy> DynamicReadOnlyCell<T> {
    /// Gets a copy of the data from the cell.
    /// Panics if the cell is not yet populated.
    #[inline(always)]
    pub fn get(&self) -> T {
        *self.get_ref()
    }

    /// Gets a copy of the data from the cell.
    /// Returns Some(T) if the cell is populated.
    /// Returns None if the cell is not populated.
    #[inline(always)]
    pub fn try_get(&self) -> Option<T> {
        self.try_get_ref().cloned()
    }
}

unsafe impl<T: Sized> Sync for DynamicReadOnlyCell<T> {}

由于原子检查和集中的关键部分,我认为这是安全的。如果您发现任何错误或躲闪的地方,请告诉我。

本文链接:https://www.f2er.com/3066109.html

大家都在问