mardi 22 mai 2018

Will relaxed memory order lead to infinite loop here?

Code in question:

#include <atomic>
#include <thread>

std::atomic_bool stop(false);

void wait_on_stop() {
  while (!stop.load(std::memory_order_relaxed));
}

int main() {
  std::thread t(wait_on_stop);
  stop.store(true, std::memory_order_relaxed);
  t.join();
}

Since std::memory_order_relaxed is used here, I assume the compiler is free to reorder stop.store() after t.join(). As a result, t.join() would never return. Is this reasoning correct?

If yes, will changing stop.store(true, std::memory_order_relaxed) to stop.store(true) solve the issue?

Aucun commentaire:

Enregistrer un commentaire