0

1) Is the following declaration of a naturally aligned pointer:

alignas(sizeof(void *)) volatile void * p;

equivalent to

std::atomic<void *> 

in C++11?

2) Saying more exactly, is it correct to assume that this type of pointer will work in the same way as std::atomic in C++11?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Alexey Starinsky
  • 3,699
  • 3
  • 21
  • 57
  • Possible duplicate of [Concurrency: Atomic and volatile in C++11 memory model](https://stackoverflow.com/questions/8819095/concurrency-atomic-and-volatile-in-c11-memory-model) – Mgetz May 22 '18 at 13:26
  • Does this answer your question? [When to use volatile with multi threading?](https://stackoverflow.com/questions/4557979/when-to-use-volatile-with-multi-threading) – Peter Cordes Dec 30 '20 at 03:25
  • Also related (for x86 specifically): [Why is integer assignment on a naturally aligned variable atomic on x86?](https://stackoverflow.com/q/36624881) – Peter Cordes Dec 30 '20 at 03:25

1 Answers1

1

No, volatile does not guarantee that the location will be written or read atomically, just the the compiler can't optimise out multiple reads and writes.

On certain architectures, the processor will atomically read or write if aligned correctly, but that is not universal or even guaranteed through a family of processors. Where it can, the internal implementation of atomic will take advantage of architectural features and atomic instruction modifiers, so why not use atomic, if you mean atomic?

Gem Taylor
  • 5,381
  • 1
  • 9
  • 27
  • Microsoft-specific ref types in C++/CX do not compile with std::atomic, and they do not have their own load/store primitives. I asked about them here: https://stackoverflow.com/questions/50349510/are-the-hat-pointers-atomic-in-c-cx. – Alexey Starinsky May 22 '18 at 13:07
  • Ah, that is a slightly different question. I don't really know M/S C# implementation in detail, but for c++ smart pointer it is not just a simple pointer, and therefore would never fit the processor's fundamental simple types, perhaps. If you can't rely on atomic then you might have to wrap it in a mutex. – Gem Taylor May 22 '18 at 15:24
  • Yes, std::mutex is my friend. – Alexey Starinsky May 22 '18 at 17:10