Skip to content

Instantly share code, notes, and snippets.

@no-longer-on-githu-b
Last active August 29, 2015 14:22
Show Gist options
  • Save no-longer-on-githu-b/39ab58cbf6995fd69817 to your computer and use it in GitHub Desktop.
Save no-longer-on-githu-b/39ab58cbf6995fd69817 to your computer and use it in GitHub Desktop.
Thread-unsafety in Rust
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let p = Arc::new(Mutex::new(0));
for _ in 1..100 {
let x = p.clone();
thread::spawn(move || {
let n;
{
let mut x_ = x.lock().unwrap();
*x_ += 1;
n = *x_;
}
thread::sleep_ms(50);
{
// because Rust guarantees thread-safety, we can safely assume x hasn't been changed
let x_ = x.lock().unwrap();
if *x_ != n {
panic!();
}
}
});
}
thread::sleep_ms(2000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment