How can old school multi-threading (no wrapping mutex) can be achieve in Rust? And why is it undefined behavior?
I have to build a highly concurrent physic simulation. I am supposed to do it in C, but I chose Rust (I really needed higher level features).
By using Rust, I should opt for a safe communication between threads, however, I must use a mutable buffer shared between the threads. (actually, I have to implement different techniques and benchmark them)
First approach
Use
Arc<Data>to share non-mutable state.Use
transmuteto promote&to&mutwhen needed.
It was straightforward but the compiler would prevent this from compiling even with unsafe block. It is because the compiler can apply optimizations knowing this data is supposedly non-mutable (maybe cached and never updated, not an expert about that).
This kind of optimizations can be stopped by Cell wrapper and others.
Second approach
Use
Arc<UnsafeCell<Data>>.Then
data.get()to access data.
This does not compile either. The reason is that UnsafeCell is not Send. The solution is to use SyncUnsafeCell but it is unstable for the moment (1.66), and the program will be compile and put to production on a machine with only the stable version.
Third approach
Use
Arc<Mutex<Data>>.At the beginning of each threads:
Lock the mutex.
Keep a
*mutby coercing a&mut.Release the mutex.
Use the
*mutwhen needed
I haven't tried this one yet, but even if it compiles, is it safe (not talking about data race) as it would be with SyncUnsafeCell ?
PS: The values concurrently mutated are just f32, there are absolutely no memory allocation or any complex operations happening concurrently. Worst case scenario, I have scrambled some f32.
SyncUnsafeCellfromstd, there doesn't seem to be anything magic about it. Btw, how about aVec<AtomicU32>(because there's noAtomicF32), and r/w to it throughf32::from/to_bits?AtomicU32actually mean compared tou32, ifu32is already atomic? Two things: volaticity (meaning: cannot be optimized into registers) and prevention of instruction reordering (hence theOrderingparameters). Apart of that,loadandstoreis identical betweenAtomicU32andu32.