rust-atomics-and-locks icon indicating copy to clipboard operation
rust-atomics-and-locks copied to clipboard

ch3-05-out-of-thin-air.rs - still don't understand 😓

Open gpawru opened this issue 9 months ago • 2 comments

The content that the question is about

use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering::Relaxed;
use std::thread;

static X: AtomicI32 = AtomicI32::new(0);
static Y: AtomicI32 = AtomicI32::new(0);

fn main() {
    let a = thread::spawn(|| {
        let x = X.load(Relaxed);
        Y.store(x, Relaxed);
    });
    let b = thread::spawn(|| {
        let y = Y.load(Relaxed);
        X.store(y, Relaxed);
    });
    a.join().unwrap();
    b.join().unwrap();
    assert_eq!(X.load(Relaxed), 0); // Might fail?
    assert_eq!(Y.load(Relaxed), 0); // Might fail?
}

The question

I still can't understand how a value different from zero can appear in the example if both x and y are initially zero, and no matter how many times you transfer 0 from one variable to another, you won't get anything other than zero? Can you explain it in more detail? It's blowing my mind 😓 Thank you!

gpawru avatar May 01 '24 07:05 gpawru

no matter how many times you transfer 0 from one variable to another, you won't get anything other than zero

Your are correct. That is not possible to fail on assert. The comment can be a bit confusing I suppose it could be rewritten as 'is that possible to fail here'? The obvious answer is no.

blandger avatar May 01 '24 08:05 blandger

@blandger Thank you very much for the response!

Chapter 3: Out-of-Thin-Air Values

Due to the lack of ordering guarantees, the load operations of these two threads might both see the result of the store operation of the other thread, allowing for a cycle in the order of operations: we store 37 in Y because we loaded 37 from X, which was stored to X because we loaded 37 from Y, which is the value we stored in Y.

Am I correct in understanding that the essence of the note 'Out-of-Thin-Air Values' is exactly what Jon Gjengset explains in this moment of the video: Crust of Rust: Atomics and Memory Ordering?

gpawru avatar May 01 '24 09:05 gpawru