Is there any option to use shared memory for Vec<f64>
in Rust?
Processes in my program swap two or more values in a Vec<f64>
and I need the memory to be shared between processes.
Is there any option to use shared memory for Vec<f64>
in Rust?
Processes in my program swap two or more values in a Vec<f64>
and I need the memory to be shared between processes.
There is no way to safely create a Vec
backed by shared memory. There are two reasons this is true:
A Vec
owns its memory and will reallocate it when grown or free it when dropped. Unsafely creating a Vec
pointing to mmap
ped memory will corrupt the heap when the Vec
reallocates or goes out of scope.
A Vec
has exclusive access to its memory, like a &mut
reference. The compiler is free to omit and reorder reads and writes based on the assumption that nothing else is using the memory. If this assumption is broken, the behavior is undefined. To relax this assumption, your data type needs to be something based on UnsafeCell
.
Vec
is the wrong pointer for this job. Try &[UnsafeCell<f64>]
, or maybe &[AtomicU64]
(with conversions using from_bits
and to_bits
), since there isn't an AtomicF64
in the standard library.