Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Atomic memory order with non-atomic variables

I am unsure about how the memory ordering guarantees of atomic variables in c++11 affect operations to other memory.

Let's say I have one thread which periodically calls the write function to update a value, and another thread which calls read to get the current value. Is it guaranteed that the effects of d = value; will not be seen before effects of a = version;, and will be seen before the effects of b = version;?

atomic<int> a {0};
atomic<int> b {0};
double d;

void write(int version, double value) {
    a = version;
    d = value;
    b = version;
}

double read() {
    int x,y;
    double ret;
    do {
        x = b;
        ret = d;
        y = a;
    } while (x != y);
    return ret;
}
like image 562
Jeffrey Dalla Tezza Avatar asked May 27 '15 18:05

Jeffrey Dalla Tezza


People also ask

Can atomic operations be reordered?

By default operations on atomic variables are done using the memory_order_seq_cst semantics, which guarantees that no reordering will be done.

Is STD atomic copyable?

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

Are memory reads Atomic?

Storing values to memory and reading values from memory are atomic operations. ¹ If a competing processor writes to or reads the same memory, the result will be completely one value or the other, never a mix of the two. This atomicity does not extend by default to read-modify-write operations, however.

What is atomic memory?

Atomic memory shrinks the number of atoms required for a bit of data to one. "There is plenty of room at the bottom": An excerpt from a landmark 1959 lecture by physicist Richard Feynman is written on a sheet of copper with chlorine atoms.


1 Answers

The rule is that, given a write thread that executes once, and nothing else that modifies a, b or d,

  • You can read a and b from a different thread at any time, and
  • if you read b and see version stored in it, then
    • You can read d; and
    • What you read will be value.

Note that whether the second part is true depends on the memory ordering; it is true with the default one (memory_order_seq_cst).

like image 74
T.C. Avatar answered Sep 19 '22 10:09

T.C.