Using relaxed memory order, e.g. for a reference counting pointer, would the compiler be allowed to optimize away a subsequent increment and decrement?
std::atomic_int32_t ai;
for (size_t i = 0; i < 10000; i++)
{
ai.fetch_add(1, std::memory_order_relaxed);
ai.fetch_sub(1, std::memory_order_relaxed);
}
Looking at disassembly it doesn't look like. But since reordering is allowed and the atomic
is behaving like a counter, just thread-safe, one could argue that he could optimize as if it would be a plain int.
std::atomic is neither copyable nor movable. The compatibility macro _Atomic is provided in <stdatomic.
Yes, it would be threadsafe. Assuming of course there are no bugs in the std::atomic implementation - but it's not usually hard to get right. This is exactly what std::atomic is meant to do.
No, fundamental data types (e.g., int , double ) are not atomic, see std::atomic .
Each instantiation and full specialization of the std::atomic template defines an atomic type. Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.
I believe it can be optimized, unless declared volatile. The reason is that for any schedule that interleaves some thread in between, there exist valid schedule that does not. I believe it to be the case for drf-sc memory model too.
It would not be the case if this thread reads something in between.
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