Variable assignment are not order guaranteed
Inspired by this document, CPU can sometimes change your execution order and compiler would optimize your code. For example
This is a reordering problem[1]
int v;
bool v_ready = false;
void threadA() {
v = 42;
v_ready = true;
}
void threadB() {
while (!v_ready) { /* wait */}
const int my_v = v;
// do something with my_v
}
In this example, we explicitly assign v_ready after v in threadA, however, due to memory locality
by the cache mechanism
, these two variable are cached in the same cache line, so this makes these variable almost value changed at the same time.
As a result, we can not guarantee v_ready is assigned after v
This brings the importance of atomicity... !
int v = 0;
std::atomic_bool v_ready(false);
void threadA() {
v = 42;
v_ready = true;
}
void threadB() {
while (!v_ready) { /* wait */}
const int my_v = v;
// do something with my_v
}
This will make sure v_ready is assigned after v ! So that threadB would get the right value of 4.