Can C ++ 11 compilers introduce extra loads of atomic variables?

In this answer , bdonlan states that the code is similar to the following:

int t; volatile int a, b; t = x; a = t; b = t; 

can be converted by the compiler to:

 a = x; b = x; 

My question is: is this allowed if x is an atomic variable with relaxed loads, as in the following?

 atomic<int> x; int t; volatile int a, b; t = x.load(std::memory_order_relaxed); a = t; b = t; assert(a == b); // Will this hold? 

As the title says, are C ++ 11 compilers allowed to introduce additional loads of atomic variables? How about extra stores?

+4
source share
1 answer

The compiler is allowed to do anything according to the as-if rule, but to load the same memory location at the same time, the compiler must show that no other thread can access the same variable. In any case, you are guaranteed that a==b in your example.

+2
source

Source: https://habr.com/ru/post/1498897/


All Articles