1 个不稳定版本
0.1.1 | 2024 年 3 月 12 日 |
---|---|
0.1.0 |
|
#13 在 #单例
10KB
102 行
Singly
简单、轻量级且“非”线程安全的单例实例,但它依赖于使用方式,有关线程安全的信息,请参阅文档,欢迎制作线程安全包装器
特性
- 使用类型设置实例的值。
- 获取实例的类型引用值。
- 获取实例的类型可变引用值。
- 在
no_std
环境中工作
示例
fn main() {
// Create the Singleton instance
let mut instance = singly::Singleton::new();
/// Set the i32 type to 12
instance.set(12i32);
/// Get mutable reference i32 type and set it to 14
let a = instance.get_mut::<i32>();
*a = 14;
assert_eq!(instance.get::<i32>(), &14);
}
安装
cargo add singly
许可证
本项目受 MIT 许可证许可
lib.rs
:
简单、轻量级且“非”线程安全的单例实例,但它依赖于使用方式,欢迎制作线程安全包装器
目前它可以在
- 使用类型设置实例的值。
- 获取实例的类型引用值。
- 获取实例的类型可变引用值。
- 无标准库环境中工作
示例
fn main() {
// Create the Singleton instance
let mut instance = singly::Singleton::new();
/// Set the i32 type to 12
instance.set(12i32);
/// Get mutable reference i32 type and set it to 14
let a = instance.get_mut::<i32>();
*a = 14;
assert_eq!(instance.get::<i32>(), &14);
}
关于线程安全的提示
- 将您的类型用 [
Arc
] 包装,然后使用Mutex
或RwLock
- 如果您可以避免使用
Singleton::get_mut
或Singleton::try_get_mut
,或者您知道自己在做什么 - 对于静态上下文中的
Singleton
实例,请使用Mutex
如果上述任何一项都没有引入,那么肯定会发生数据竞争
并发场景示例
use std::{
sync::{Arc, Mutex},
thread::spawn,
};
use singly::Singleton;
struct Counter(i32);
// Notice on the type
type ArcMutexCounter = Arc<Mutex<Counter>>;
fn main() {
let mut instance = Singleton::new();
let counter = Arc::new(Mutex::new(Counter(0)));
instance.set(counter);
let mut handles = vec![];
for _ in 0..10 {
let counter_clone: ArcMutexCounter = Arc::clone(instance.get::<ArcMutexCounter>());
let handle = spawn(move || {
let mut counter = counter_clone.lock().unwrap();
(*counter).0 += 1;
});
handles.push(handle);
}
let _ = handles
.into_iter()
.map(|handle| handle.join())
.collect::<Result<Vec<_>, _>>();
let counter = instance.get::<ArcMutexCounter>().lock().unwrap().0;
assert_eq!(counter, 10);
}
在 integration_test.rs 中有示例
依赖
~2MB
~26K SLoC