2

Does std::atomic play well in shared memory, or is it undefined? It seems like an easy way to add lockless basic types to shared memory however I could believe that it's not possible to guarantee atomic behaviour in the context of shared memory.

Joe
  • 7,378
  • 4
  • 37
  • 54

2 Answers2

3

Why not, you just need to allocate and construct it inside the shared memory region properly.

Anton
  • 6,349
  • 1
  • 25
  • 53
2

It depends.

If the architecture you are using supports atomic operations on 64-bit types, I would expect it to work. If std::atomic is simulating atomic operations with mutexes then you will have a problem:

  • Shared memory is usually used to communicate between processes - and the mutex being used may only work between threads in a single process (for example the Windows CriticalSection API).
  • Alternatively, shared memory is quite likely to be mapped at different addresses in different processes, and the mutex may have internal pointers which mean that doesn't work.