0

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.

trent
  • 25,033
  • 7
  • 51
  • 90
Mateusz Piwowarski
  • 559
  • 1
  • 6
  • 15
  • 1
    Not relevant to your case, but for those who might accidentally stumble on this question: [How do I pass disjoint slices from a vector to different threads?](https://stackoverflow.com/q/33818141/155423); [How can I pass a reference to a stack variable to a thread?](https://stackoverflow.com/q/32750829/155423); [How can I mutably share an i32 between threads?](https://stackoverflow.com/q/42849210/155423) – Shepmaster Dec 15 '19 at 22:13
  • What kind of changes -- do they only mutate items in the `Vec`, or do they add and remove items from the `Vec` itself? – trent Dec 15 '19 at 22:43
  • They swap two or more values in my vector. – Mateusz Piwowarski Dec 15 '19 at 22:55
  • 3
    Are we talking shared between *processes* or between *threads*? Threads share memory normally, with processes you have to set it up with system calls and things. It's a lot more difficult. – trent Dec 16 '19 at 00:11
  • Shared memory between processes. – Mateusz Piwowarski Dec 16 '19 at 08:34

1 Answers1

1

There is no way to safely create a Vec backed by shared memory. There are two reasons this is true:

  1. A Vec owns its memory and will reallocate it when grown or free it when dropped. Unsafely creating a Vec pointing to mmapped memory will corrupt the heap when the Vec reallocates or goes out of scope.

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

trent
  • 25,033
  • 7
  • 51
  • 90