Skip to content

Instantly share code, notes, and snippets.

Created February 21, 2017 17:23
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 anonymous/0b5a75a34c81f63206ff8078078cee59 to your computer and use it in GitHub Desktop.
Save anonymous/0b5a75a34c81f63206ff8078078cee59 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
use std::thread;
use std::sync::{Arc, Mutex, Condvar};
use std::{time};
#[derive(PartialEq,Debug)]
enum Command {
Idle,
Busy,
}
fn poll_thread(sync_pair: Arc<(Mutex<Command>, Condvar)> )
{
let &(ref mutex, ref cvar) = &*sync_pair;
loop {
let mut flag = mutex.lock().unwrap();
while *flag == Command::Idle {
println!(" Waiting for non-idle state");
flag = cvar.wait(flag).unwrap();
}
match *flag {
Command::Idle => {panic!("WHAT IMPOSSIBLE!");},
Command::Busy => {
thread::sleep(time::Duration::from_millis(4));
},
}
}
}
pub fn main() {
println!("---------------------------------");
println!("main_thread loop_thread");
println!("---------------------------------");
let pair = Arc::new((Mutex::new(Command::Idle), Condvar::new()));
let pclone = pair.clone();
let rx_thread = thread::spawn( || poll_thread(pclone) );
let &(ref mutex, ref cvar) = &*pair;
for i in 0..10 {
thread::sleep(time::Duration::from_millis(10));
println!("i = {}", i);
if i == 2 {
println!("Setting Busy");
let mut flag = mutex.lock().unwrap();
*flag = Command::Busy;
println!("flag is = {:?}", *flag);
cvar.notify_one();
}
else if i == 4 {
println!("Setting Idle");
let mut flag = mutex.lock().unwrap();
println!("Got mutex");
*flag = Command::Idle;
println!("flag is = {:?}", *flag);
cvar.notify_one();
}
}
println!("completed loop.");
rx_thread.join().unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment