Last active
August 29, 2015 14:22
-
-
Save no-longer-on-githu-b/39ab58cbf6995fd69817 to your computer and use it in GitHub Desktop.
Thread-unsafety in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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