Crate syncrs

Source
Expand description

Spinlock-based synchronization primitives

The following synchronization primitives are implemented

§Examples

§Mutex

use syncrs::{Mutex, LazyLock};

static N: Mutex<u32> = Mutex::new(0);

let threads = (0..10).map(|_|{
    std::thread::spawn(move || {
        let mut sync_n = N.lock();
        for _ in 0..10 {
            *sync_n += 1;
        }
    })
}).collect::<Vec<_>>();

for t in threads {
    t.join().unwrap();
}

assert_eq!(*N.lock(), 100);

§LazyLock

use syncrs::LazyLock;
use std::collections::HashMap;

static MAP: LazyLock<HashMap<i32, String>> = LazyLock::new(|| {
    let mut map = HashMap::new();
    for n in 0..10 {
        map.insert(n, format!("{n}"));
    }
    map
});

let map = MAP.get(); /* MAP is initialized at this point */
assert_eq!(
    map.get(&4).map(|s| s.as_str()),
    Some("4"),
);

Re-exports§

pub use mutex::Mutex;
pub use rwlock::RwLock;
pub use condvar::Condvar;

Modules§

condvar
Conditional Variable
mutex
A mutex, providing unique syncronized access to a value
rwlock
A read-write lock
spin
A spinlock, the core primitive of this crate

Structs§

LazyLock
A synchronization primitive that is lazily initialized on its first access
OnceLock
A synchronization primitive that can only be written to once
Semaphore
A semaphore