-
Notifications
You must be signed in to change notification settings - Fork 13.6k
Closed
Description
According to the Rust website, Rust guarantees thread safety. However, I managed to write a program that appears to be thread-unsafe while it does not use external resources or unsafe
:
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);
}
Expected output:
No output and exit status 0.
Actual output:
This program panics.
Metadata
Metadata
Assignees
Labels
No labels