Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can std::atomic cancel out increments with decrements?

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.

like image 844
Borph Avatar asked Aug 04 '16 11:08

Borph


People also ask

Is STD atomic copyable?

std::atomic is neither copyable nor movable. The compatibility macro _Atomic is provided in <stdatomic.

Is STD atomic thread safe?

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.

Is unsigned int Atomic?

No, fundamental data types (e.g., int , double ) are not atomic, see std::atomic .

What does std :: atomic do?

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.


1 Answers

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.

like image 76
Elazar Avatar answered Sep 24 '22 14:09

Elazar