Skip to content

Instantly share code, notes, and snippets.

@faern
Created April 11, 2019 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faern/ef28bd61ea49649663152dae9da47309 to your computer and use it in GitHub Desktop.
Save faern/ef28bd61ea49649663152dae9da47309 to your computer and use it in GitHub Desktop.
use parking_lot::{Mutex, Condvar}; // 0.7.1
use std::{thread, sync::Arc, time::Duration};
fn main() {
let locks = Arc::new((Mutex::new(()), Condvar::new()));
for i in 0..4 {
let locks = locks.clone();
let t = thread::spawn(move || {
let mut guard = locks.0.lock();
println!("Thread {} waiting", i);
locks.1.wait(&mut guard);
// Comment out the following wait to make it work
println!("Thread {} waiting for 1ms", i);
locks.1.wait_for(&mut guard, Duration::from_millis(1));
println!("Thread {} notifying next: {}", i, locks.1.notify_one());
});
}
thread::sleep(Duration::from_millis(100));
locks.1.notify_one();
thread::sleep(Duration::from_millis(1000));
println!("main exiting");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment