Why do Rust's `Atomic*` types use non-mutable functions to mutate the value?

Viewed 893

I notice that Rust's Atomic* structs have functions which modify the value, such as fetch_add. For instance, I can write this program:

use std::sync::atomic::{AtomicUsize, Ordering};

struct Tester {
    counter: AtomicUsize
}

impl Tester {
    fn run(&self) {
        let counter = self.counter.fetch_add(1, Ordering::Relaxed);
        println!("Hi there, this has been run {} times", counter);
    }
}

fn main() {
    let t = Tester { counter: AtomicUsize::new(0) };
    t.run();
    t.run();
}

This compiles and runs fine, but if I change the AtomicUsize to a normal integer, it will (correctly) fail to compile due to mutability concerns:

struct Tester {
    counter: u64
}

impl Tester {
    fn run(&self) {
        self.counter = self.counter + 1;
        println!("Hi there, this has been run {} times", self.counter);
    }
}
1 Answers
Related