#global #rw-lock #sync #mutex #tokio #global-container

simple-rw-global

基于 std::sync::RwLock 的简单 GlobalContainer

6 个版本 (破坏性更新)

0.5.0 2023 年 9 月 30 日
0.4.0 2023 年 5 月 26 日
0.3.0 2023 年 5 月 26 日
0.2.1 2023 年 5 月 26 日
0.1.0 2023 年 5 月 20 日

#566并发

每月 22 次下载

MIT 许可证

12KB
216

simple-rw-global

现状。

基于 std::sync::RwLock.


lib.rs:

基于 std::sync::RwLock 的简单 GlobalContainer。

此 crate 现状。

注意: GlobalContainer 使用 RWLockGlobalMutexContainer 使用 Mutex

作者:ZRY。

功能

tokio

对于 tokio,使用功能 tokio

[dependency]
simple-rw-global = { version="0.3.0", feature=["tokio"] }

使用此功能,模块 tokio 可用。

示例

use simple_rw_global::GlobalContainer;

static GLOBAL : GlobalContainer<GlobalObject> = GlobalContainer::<GlobalObject>::new();

pub struct GlobalObject {
    log_prefix: String,
}

impl GlobalObject {
    pub fn new(prefix: &str) -> GlobalObject {
        GlobalObject{log_prefix: String::from(prefix)}
    }

    pub fn log(&self, msg: &str) {
        println!("[{}] {}", self.log_prefix.as_str(), msg);
    }

    pub fn change_prefix(&mut self, prefix: &str) {
        self.log_prefix = String::from(prefix);
    }
}

fn main() {
    println!("before init, is empty: {}", GLOBAL.is_empty());
    GLOBAL.set(GlobalObject::new("log-test1"));
    println!("after init, is empty: {}", GLOBAL.is_empty());
    println!("init ok.");
    GLOBAL.get().log("hello 1");
    GLOBAL.get_mut().change_prefix("log-test2");
    GLOBAL.get().log("hello 2");
    GLOBAL.manual_drop();
    println!("dropped manually. will panic then.");
    GLOBAL.get().log("test after drop.");
}

依赖

~0–1.1MB
~19K SLoC