0

Suppose I have an atomic variable aa and a non-atomic variable na. Is it possible to ensure that the atomic variable aa is read AFTER na?

In general, an acquire memory fence prevents loads from being reordered. Will it ensure ordering also in this case? If not, is it possible to achieve this ordering without making na atomic and without using a strong memory fence (i.e., sequential consistency) for the reader, which is significantly more expansive?

int na{0}; 
atomic<int> aa{0}; 

void thread1(){
    int l1 = na; 
    std::signal_memory_fence(std::memory_order_acquire); 
    int l2 = aa;
    assert( l2==0 || l1==1 ); //does this hold?
    //if reading from aa observed the latest value 1, reading from na cannot have an earlier value 
}
void thread2(){
    aa.store(1, std::memory_order_seq_cst); 
    na = 1; 
}

Thanks

P.S. The main difference from the following question Re-ordering Atomic Reads is that the first variable is assumed to be non atomic.

Nachshon Cohen
  • 113
  • 2
  • 10
  • 1
    If the first variable is assumed to be non-atomic, the code becomes illegal since you need protection for this variable – LWimsey Jun 07 '18 at 03:11
  • This works on x86 and I assume on any architecture that does not reorder reads. The question is if this is guaranteed by c++11 – Nachshon Cohen Jun 07 '18 at 03:46
  • `na` must be atomic, or you have undefined behavior. On `X86`, you'll probably get away with declaring it `volatile`. Since `X86` preserves the order of 2 independent stores, thread1 will observe them in the order as committed by thread2 (the compiler may still reorder your stores, even with the seq/cst store on `aa`, although unlikely). But even with no reordering at all, the assert can fire on `l2==1` and `l1==0` since that is a legitimate outcome. – LWimsey Jun 07 '18 at 05:01

0 Answers0