Skip to content

Instantly share code, notes, and snippets.

@dulimarta
Created January 28, 2020 21:34
Show Gist options
  • Save dulimarta/a5f82600de668edbf12413eb709bff66 to your computer and use it in GitHub Desktop.
Save dulimarta/a5f82600de668edbf12413eb709bff66 to your computer and use it in GitHub Desktop.
CS452 Lab04 - Sample 3 (Rust)
use nix::unistd::sleep;
use std::thread;
// Global variable
static mut SHARED_DATA: u8 = 5;
fn main() {
// Use lambda when the thread function takes arguments
let thr1 = thread::spawn(|| do_greeting3('a'));
let thr2 = thread::spawn(|| do_greeting3('b'));
unsafe {
println!("Parent sees {}", SHARED_DATA);
SHARED_DATA += 1;
}
thr1.join().expect("Can't join");
thr2.join().expect("Can't join");
unsafe {
println!("Parent sees {}", SHARED_DATA);
}
}
fn do_greeting3(arg: char) {
unsafe {
println!("Child receiving {} initially sees {}", arg, SHARED_DATA);
sleep(1);
SHARED_DATA += 1;
println!("Child receiving {} now sees {}", arg, SHARED_DATA);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment