Something akin to a Readback in Rust

I am trying to write a Rust program in a multi-threaded environment which, directly after writing a value to a variable, reads the variable again. That way the writing of the variable won't be too asynchronous, as the writing must be finished before I read it again. Problem is, it seems that the compiler optimizes the read line out of the program, as it basically does nothing.
Is there any way to still achieve the above mentioned goal?

So something like this:

pub fn main(){
let x:i32 = 5; //Set the variable
x; //Just read it again so the writing must be finished, but without this line getting optimized out
}

Thanks in advance, I hope my problem is portrayed understandably!

If you are accessing a value from multiple threads, then you must use atomic types (or other appropriate synchronization). When you do, the optimizer will not interfere with your use of them.

4 Likes

That way the writing of the variable won't be too asynchronous, as the writing must be finished before I read it again.

You seem to have an incorrect understanding how memory and concurrency work in modern computers and also how compilers handle concurrent code.

You may want to read the fearless concurrency chapter in the rust book, "Rust Atomics and Locks" by Mara Bos or similar resources.

In safe Rust it's quite simple: You cannot have data races because they're undefined behavior.

Which means you won't have to "convince" the compiler to order something properly with some underhanded trickery. Either it compiles or you'll get an error. E.g. if you use scoped threads then the closure captures of the spawn scope will ensure proper shared-xor-mutable and happens-before semantics so that something initialized before the scope will be visible to all threads in the scope and cannot be modifed unless you use something like atomics or locks - both found in the std::sync module - that provide explicit ordering guarantees.

CPUs and optimizing compilers will treat memory operations as local by default and you must use explicit constructs to tell them otherwise.

3 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.