#![allow(unused)]
fn main() {
use std::sync::{Arc, Mutex, Condvar};
use std::thread;
use std::time::Duration;
use std::thread::sleep;
let pair = Arc::new((Mutex::new(false), Condvar::new()));
let pair2 = pair.clone();
// Inside of our lock, spawn a new thread, and then wait for it to start.
thread::spawn(move|| {
let &(ref lock, ref cvar) = &*pair2;
sleep(Duration::from_secs(1));
println!("t try lock");
let mut started = lock.lock().unwrap();
println!("t locked");
*started = true;
// We notify the condvar that the value has changed.
cvar.notify_one();
println!("t unlocking");
});
// Wait for the thread to start up.
let &(ref lock, ref cvar) = &*pair;
let mut started = lock.lock().unwrap();
println!("main locked");
while !*started {
started = cvar.wait(started).unwrap();
}
println!("main unlocking");
}
Here is the output:
main locked
t try lock
t locked
t unlocking
main unlocking