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

问题描述 投票:2回答:1

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

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来共享变量?

rust embedded mutex cortex-m
1个回答
0
投票

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

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.
    pub fn get_ref(&self) -> &T {
        if !self.is_populated.load(Ordering::Acquire) {
            panic!("Trying to get when the cell hasn't been populated yet");
        }

        unsafe { self.data.get().as_ref().unwrap().as_ref().unwrap() }
    }

    /// 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.
    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.
    pub fn get(&self) -> T {
        if !self.is_populated.load(Ordering::Acquire) {
            panic!("Trying to get when the cell hasn't been populated yet");
        }

        unsafe { self.data.get().read().unwrap() }
    }

    /// 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.
    pub fn try_get(&self) -> Option<T> {
        if !self.is_populated.load(Ordering::Acquire) {
            None
        } else {
            Some(unsafe { self.data.get().read().unwrap() })
        }
    }
}

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

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

© www.soinside.com 2019 - 2024. All rights reserved.