11 个版本
0.4.3 | 2021 年 9 月 6 日 |
---|---|
0.4.2 | 2021 年 4 月 27 日 |
0.4.1 | 2020 年 11 月 16 日 |
0.3.1 | 2020 年 9 月 11 日 |
0.0.2 | 2019 年 7 月 29 日 |
#1774 in 嵌入式开发
81 每月下载
用于 7 个 Crates(6 个直接使用)
14KB
104 行
RusPiRo Singleton crate
此 crate 提供了一个易于使用且在跨核心使用时安全的单例模式。
用法
要使用此 crate,只需将其依赖项添加到您的 Cargo.toml
文件中
[dependencies]
ruspiro-singleton = "0.4.3"
完成之后,在任何 Rust 文件中,您都可以以两种不同的方式定义任何类型的静态变量为 Singleton
,以实现跨核心的安全访问。第一种变体需要在定义时提供要包装在单例内部的数据实例。
// define the static variable
static DEMO:Singleton<Demo> = Singleton::new(Demo::new());
// define the type to be accessible as singleton
struct Demo {
pub count: u32,
}
// implement the type that should provided as singlton
impl Demo {
pub const fn new() -> Self {
Demo {
count: 0,
}
}
}
第二种变体允许在 Singleton
的初始化时传递一个闭包,该闭包将在首次访问其内容时执行。
!提示!使用原子操作确保了安全的延迟初始化。在 Raspberry Pi 上,原子操作需要配置并激活 MMU。否则,尝试执行原子操作时,执行 CPU 核心将挂起。
// define the static variable with an inizialization closure
static DEMO:Singleton<Box<Demo>> = Singleton::lazy(&|| {
Box::new(
Demo::new()
)
});
// define the type to be accessible as singleton
struct Demo {
pub count: u32,
}
// implement the type that should provided as singlton
impl Demo {
pub const fn new() -> Self {
Demo {
count: 0,
}
};
}
要使用使用 Singleton
封装的数据,请调用两种方法之一 with_ref
和 with_mut
,提供访问数据的不可变或可变闭包。
fn main() {
// safely use the singleton inside the closure passed to [with_mut] to update it's contents
DEMO.with_mut(|d| {
d.count += 10;
});
// safely use the singleton inside the closure passed to [with_ref] if read-only access is required
DEMO.with_mut(|d| {
println!("Value: {}", d.count);
});
// you may also return a value from the singleton to work with it after the safe singleton access
let val = DEMO.with_ref(|d| {
if d.count != 0 {
true
} else {
false
}
});
}
许可证
根据 Apache 许可证第 2 版,(LICENSE-APACHE 或 https://apache.ac.cn/licenses/LICENSE-2.0) 或 MIT (LICENSE-MIT 或 http://opensource.org/licenses/MIT)),任选其一。
依赖项
~60KB