Loading an atomic after store returns old value

I have the following code

const VOLUME: AtomicI8 = AtomicI8::new(127);
const VOL_MULTIPLIER: i8 = 3;

fn change_volume(msg: Msg) -> i8 {
    let old_volume = VOLUME.load(Ordering::SeqCst);
    let new_volume = match msg {
        Msg::Up => old_volume.saturating_add(1 * VOL_MULTIPLIER),
        Msg::Down => old_volume.saturating_sub(1 * VOL_MULTIPLIER).max(0),
    };
    VOLUME.store(new_volume, Ordering::SeqCst);
    debug_assert_eq!(new_volume, VOLUME.load(Ordering::SeqCst));
    new_volume
}

and the assertion fails every time. I’m really confused because my load is after a store that set it to the value I’m testing against! Any ideas?

1 Like

I’ve solve it!

const doesn’t just mean immutable, it means substituted into the binary at each place its used. So all my uses of VOLUME are operating on different instances of AtomicI8.

I’d guess that having a const Atomic* is always a bug, maybe it could have a lint warning?

1 Like

Yeah, a lint would be great: https://github.com/rust-lang/rust/issues/40543

4 Likes