How does the compiler know not to optimize out reads on atomic_bool?

Viewed 108

Assuming a thread running indefinitely until it's member variable stop is set. Like

while (!stop) {
  // do something
}

When stop is a simple boolean, the compiler can apparently do something like this

if (!stop) {
  while (true) {
  
  }
}

So even if another thread sets stop to true, it might have no effect at all.
But as far as I understood, using std::atomic<bool> does prevent the compiler from performing this optimization.

Question is: how?

0 Answers
Related