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;
}
By default operations on atomic variables are done using the memory_order_seq_cst semantics, which guarantees that no reordering will be done.
std::atomic is neither copyable nor movable. The compatibility macro _Atomic is provided in <stdatomic.
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.
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.
The rule is that, given a write
thread that executes once, and nothing else that modifies a
, b
or d
,
a
and b
from a different thread at any time, andb
and see version
stored in it, then
d
; andvalue
.Note that whether the second part is true depends on the memory ordering; it is true with the default one (memory_order_seq_cst
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With