Created
January 31, 2025 22:44
-
-
Save paulc/2c8b868fb464de2223200034e5bfa410 to your computer and use it in GitHub Desktop.
Rust Condvar Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::sync::{Arc, Condvar, Mutex}; | |
use std::thread; | |
use std::time::Duration; | |
static GUARD: Mutex<Option<Arc<(Mutex<u8>, Condvar)>>> = Mutex::new(None); | |
fn main() { | |
let guard = Arc::new((Mutex::new(0), Condvar::new())); | |
let guard_thread = guard.clone(); | |
{ | |
let mut guard_static = GUARD.lock().unwrap(); | |
*guard_static = Some(guard.clone()); | |
} | |
thread::spawn(move || { | |
let (lock, cvar) = &*guard_thread; | |
loop { | |
{ | |
let mut counter = lock.lock().unwrap(); | |
*counter += 1; | |
// We notify the condvar that the value has changed. | |
cvar.notify_one(); | |
} | |
println!(">> Notify"); | |
thread::sleep(Duration::from_millis(1000)); | |
} | |
}); | |
let rx = thread::spawn(|| { | |
// Lock the GUARD to access its contents | |
let guard = GUARD.lock().unwrap(); | |
// Unwrap the Option to get the Arc<(Mutex<bool>, Condvar)> | |
let guard = guard.as_ref().unwrap(); | |
// Dereference the Arc to get the tuple (Mutex<bool>, Condvar) | |
let (lock, cvar) = &**guard; | |
loop { | |
let started = lock.lock().unwrap(); | |
let result = cvar | |
.wait_timeout(started, Duration::from_millis(200)) | |
.unwrap(); | |
if !result.1.timed_out() { | |
println!(">> Wake -- Counter: {}", result.0); | |
} else { | |
println!(">> Timeout"); | |
} | |
} | |
}); | |
rx.join().unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment