I need to do some high bit rate streaming between two processes on the same machine. In order to avoid excessive copying my idea is to allocate a large shared memory buffer (via CreateFileMapping) which will contain the actual data, and use a pipe for control messages.
The idea is that the producer will write a chunk of data to the shared memory then send a message over the pipe, effectively passing ownership to the consumer. The consumer does its business directly on the shared memory, then sends another message to release the memory back to the producer. Repeat ad infinitum.
Is this synchronisation mechanism guaranteed to be safe in terms of memory coherency? I.e., is the consumer guaranteed to see the complete effects of the producer's writes after receiving the control message?
For practical purposes, shared memory across processes has the same properties as normal memory shared by two threads of a single process. That is to say, you theoretically need a memory fence/barrier. I suspect that in practice the IPC control message will suffice.
At the CPU level, shared memory is physically the same RAM in both processes. It is just a matter of having compatible virtual-to-physical mappings in the respective page tables.
From MSDN:
With one important exception, file views derived from any file mapping object that is backed by the same file are coherent or identical at a specific time. Coherency is guaranteed for views within a process and for views that are mapped by different processes.
The exception is related to remote files.
Even if this weren't guaranteed, MSalters is correct that sending the message through the named pipe is almost certainly enough of a barrier to ensure that the data that has been written to the shared memory is ready to be read by another process.
Also, I've worked on an application that handled IPC exactly as you've described, and there were never any bugs related to data races.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With