Can std :: atomic cancel decrement increments?

Using a relaxed memory order , for example. for a reference count pointer, will the compiler be allowed to optimize 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 a showdown, it doesn't look like it. But since reordering is allowed and atomic behaves like a counter, just thread-safe, it can be argued that it could optimize as if it were a simple int.

+8
c ++ compiler-optimization multithreading atomic c ++ 11
source share
2 answers

I believe that it can be optimized if it is not declared mutable. The reason is that for any schedule that interleaves a stream between them, there is a valid schedule that does not. I believe this also applies to the drf-sc memory model.

This is not the case if this thread is reading something in between.

+4
source share

the compiler cannot optimize atomics, as this will violate what they are intended for. He must assume that another thread might touch the value, so deletion is not allowed.

it also cannot optimize / reorder material that is "visible" to C ++ code from beginning to end (and vice versa), since atomization is a memory barrier.

-3
source share

All Articles