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

simple-rw-global

Simple GlobalContainer based on std::sync::RwLock

6 releases (breaking)

0.5.0 Sep 30, 2023
0.4.0 May 26, 2023
0.3.0 May 26, 2023
0.2.1 May 26, 2023
0.1.0 May 20, 2023

#370 in Concurrency

Download history 3/week @ 2024-02-18 2/week @ 2024-02-25 43/week @ 2024-03-10 2/week @ 2024-03-17 54/week @ 2024-03-31

99 downloads per month

MIT license

12KB
216 lines

simple-rw-global

As is.

Based on std::sync::RwLock.


lib.rs:

Simple GlobalContainer based on std::sync::RwLock.

This crate is AS IS.

NOTE: GlobalContainer use RWLock, GlobalMutexContainer use Mutex.

By ZRY.

Features

tokio

For tokio, use feature tokio

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

With this feature, module tokio is available.

Example

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.");
}

Dependencies

~0–1.1MB
~19K SLoC