Skip to content

Instantly share code, notes, and snippets.

@Archina
Created September 4, 2017 18:19
Show Gist options
  • Save Archina/71529db1ebdc9936b91eff1af862afa0 to your computer and use it in GitHub Desktop.
Save Archina/71529db1ebdc9936b91eff1af862afa0 to your computer and use it in GitHub Desktop.
Playing around with threads in rust....
use std::sync::*;
use std::thread;
fn main() {
let mut x = 12;
let y = x; // This copies
x = 16; //
#[derive(Debug)]
struct Chicken{
number_of_bones: u32,
}
println!("x: {}, y: {}",x,y);
let chi = Chicken{number_of_bones:32};
println!("{:?}",chi);
let val = 12;
let a = Arc::new(Mutex::new(val));
let b = a.clone();
println!("a: {:?}, b: {:?}",a,b);
*b.lock().unwrap() = 33;
println!("a: {:?}, b: {:?}",a,b);
// Threads:
let smart_pair = Arc::new( ( Mutex::new(33), Condvar::new() ) );
for _ in 0..10 {
let tmp = smart_pair.clone();
thread::spawn(move || {
let &(ref lock, ref cvar) = &*tmp;
{
let mut started = lock.lock().unwrap();
*started += 21;
}
// We notify the condvar that the value has changed.
cvar.notify_one();
println!("{:?}", lock);
});
}
thread::sleep(std::time::Duration::from_millis(1000));
let (ref left,_) = *smart_pair;
println!("{:?}",left);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment