I'm reading Stroustrup C++ 4th Ed Page 1204 and the following example is used. I'm curious, what would be the possible re-ordering of this code? Is it optimization? If so, for example, would making volatile bool x_init
also prevent the optimization or reordering?
X x;
mutex lx;
atomic<bool> x_init {false};
void some_code()
{
if (!x_init) {
lx.lock();
if (!x_init) {
// ... initialize x ...
x_init = true;
}
lx.unlock();
}
// ... use x ...
}
Stroustrup Quote:
Had init_x not been atomic, instruction reordering could have moved the initialization of x ahead of the apparently unrelated test of init_x. Making init_x atomic prevents that.