1

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.

notaorb
  • 1,944
  • 1
  • 8
  • 18
  • `volatile` doesn't give strong enough guarantees when multithreading. Here's some reading on `volatile`: https://stackoverflow.com/a/4437555/4581301 and https://stackoverflow.com/a/5190753/4581301 Specifically, `volatile` will not prevent re-ordering. – user4581301 Aug 08 '20 at 19:43
  • If multiple threads may call `some_code` simultaneously, and `x_init` is not of `atomic` type, then such a program would exhibit undefined behavior by way of a data race. Beyond that, I'm not sure I understand your question. – Igor Tandetnik Aug 08 '20 at 19:44
  • @IgorTandetnik my question is specific to Stroustrup's mention of instruction reordering and what could be reordered – notaorb Aug 08 '20 at 19:54
  • @user4581301 I was thinking of the how the code would be reordered if atomic had not been used, and using volatile and removal of volatile as another mechanism to explain possible reordering – notaorb Aug 08 '20 at 20:01
  • Forget about volatile. It has nothing to do with atomicity. Only time you should really be using volatile is when working with hardware. – Taekahn Aug 08 '20 at 20:05

0 Answers0