Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
gpawru opened this issue May 1, 2024 · 2 comments
Open

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

gpawru opened this issue May 1, 2024 · 2 comments
Labels

Comments

@gpawru
Copy link

gpawru commented May 1, 2024

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 gpawru added the question label May 1, 2024
@blandger
Copy link

blandger commented May 1, 2024

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.

@gpawru
Copy link
Author

gpawru commented May 1, 2024

@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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants