microlock/examples/channel.rs

30 lines
790 B
Rust
Raw Permalink Normal View History

2024-07-14 01:58:49 +02:00
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());
2024-07-14 10:12:39 +02:00
// try_lock because another unlock *could*ve happened since then
LOCK.try_lock();
2024-07-14 01:58:49 +02:00
});
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();
}
}