#synchronization #lock #waiting #channel #timer #thread #untimed-lock

microlock

A crate for waiting: Small locks and other timing things!

3 unstable releases

0.2.1 Jul 14, 2024
0.2.0 Jul 14, 2024
0.1.0 Jul 14, 2024

#676 in Concurrency

Download history 295/week @ 2024-07-12 15/week @ 2024-07-19 4/week @ 2024-07-26 1/week @ 2024-08-02 39/week @ 2024-09-13 18/week @ 2024-09-20 4/week @ 2024-09-27

61 downloads per month

MIT license

15KB
299 lines

microlock

Microlock is a smallish crate for waiting. It contains an UntimedLock suitable for complex synchronization, and a TimedLock that can also function as such, but additionally provides timer functionalities.

Use-case:

The untimed lock can be used similarly to a channel, with added flexibility. In this example, it simply replaces a channel, but more complex use-cases are significantly less trivial with channels.

use std::{
    collections::VecDeque,
    sync::{Arc, Mutex},
    thread,
};

use microlock::{Lock, TimedLock, UntimedLock};

fn main() {
    static LOCK: UntimedLock = UntimedLock::locked();
    let queue = Arc::new(Mutex::new(VecDeque::new()));
    let queue2 = queue.clone();
    thread::spawn(move || loop {
        LOCK.wait_here();
        println!("{}", queue2.lock().unwrap().pop_front().unwrap());
        LOCK.lock();
    });

    let timer = TimedLock::unlocked();
    for i in 0..5 {
        timer.lock_for_ms(100);
        println!("Sending {i}...");
        queue.lock().unwrap().push_back(format!("Hello! {i}"));
        LOCK.unlock();
        println!("Sent!");
        timer.wait_here();
    }
}

No runtime deps