Skip to content

Rust does not guarantee thread-safety #26215

@no-longer-on-githu-b

Description

@no-longer-on-githu-b

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions