What C++ construct should be used to access memory shared with another process [duplicate]
Asked Answered
D

0

7

How should C++ code access memory that is shared with another application, e.g. through a memmapd file? The options seem to be:

  1. Regular raw accesses, e.g. int* p = ...address of shared memory...; *p = 5; *p. This seems unsafe because the compiler is allowed to assume that the contents of p are stable which is not the true.
  2. One way to think of these operations is that they are input/output to another process, so (at least in old versions of C++) the way that this should be achieved seems to be with volatile.
  3. Since modern-C++ contains builtin atomic operations, another option is to use atomics. In practice, compilers don't seem to do much optimization around these operations, but it isn't clear that it is forbidden by the standard.

From experiments, it seems that both 2 and 3 work in practice (2 not properly handling the intricacies of weak memory), but is either standards compliant? Do I need to use a combination, i.e. accesses to atomic<volatile int>?

Dragoman answered 22/7, 2021 at 3:3 Comment(4)
C++ standard doesn't know such thing as an object shared between two instances of an abstract machine. The closes proposal I know is p1631, but it doesn't seem to allow using the same object simultaneously, only passing it back and forth.Shotten
atomics don't need volatile. Atomics may have internal structure and could break in interesting ways if used with shared memory (the "does not require" in the linked doc is a bit worrying). I would stick to C-style data types and volatile for now.Threadbare
I should probably add that I only need to perform accesses on primitives, e.g. atomic<int>, atomic<long>, etc. I need to make the assumption that these are all lock free. I could also do the atomic compiler builtins directly, but the standard doesn't say anything about those.Dragoman
Near duplicate of Are lock-free atomics address-free in practice? - yes it works. And see comments on Is using volatile on shared memory safe?Gendarmerie

© 2022 - 2024 — McMap. All rights reserved.