I'm having trouble wrapping my head around the correct usage of std::atomic_ref<int>
with volatile
.
Naively there are three possibilities:
std::atomic_ref<volatile int> ref1;
volatile std::atomic_ref<int> ref2;
volatile std::atomic_ref<volatile int> ref3;
When and do we want to use each one? The use-case I'm interested in is MMIO.
Unlike std::atomic<T>
, std::atomic_ref<T>
does not have volatile
-qualified methods. So, you probably can't do much with a volatile std::atomic_ref<T>
(whether T is itself volatile or not).
This makes sense given the quote
Like language references, constness is shallow for atomic_ref - it is possible to modify the referenced value through a const atomic_ref object.
Assuming cv-qualification is somewhat consistent, a shallowly-volatile atomic_ref is unlikely to be useful, and definitely isn't what you're asking for.
So, you want
std::atomic_ref<volatile int>
Note that it may be sufficient to just use std::atomic_ref<int>
, but since the standard doesn't make any explicit guarantees about MMIO, you should probably consult your compiler documentation and/or check the code it generates.
Depending on std::atomic
in this way is at least not portable. Specifically, this answer and its linked paper mention some ways in which std::atomic
may be inadequate - you can check whether these are actual problems for you.
Follow-up to the main comment chain, which confuses MMIO and mmap'd IPC: these are completely different.
Atomics control how loads & stores interact with the processor's native memory & coherence model.
IPC happens entirely within the CPU & its memory controller, so atomics are sufficient.
This is what OP actually wanted, and has no need for volatile
.
MMIO (as originally requested) is about addressing I/O devices outside the purview of the processor's coherence model.
It isn't real memory, doesn't behave like real memory, and you may need volatile
.
This is what OP asked for, but not what they wanted.
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