Do const atomics update?

Suppose I want a global atomic. How do I implement that. I tried as below, and the unique ID is always the same.


const NEXT_UNIQUE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

fn main() {
    println!("{:?} {:?} {:?}",
        NEXT_UNIQUE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
        NEXT_UNIQUE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
        NEXT_UNIQUE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
    );
}

I tried with all kinds of std::sync::atomic::Ordering too

const items get inlined wherever they are used, so each line in the code is essentially a copy-paste of AtomicU64::new(0). If you want a globally unique value, use static.

static NEXT_UNIQUE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
7 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.