Atomic/not-atomic mix, any guarantees?

126 views Asked by At

Let's I have GUI thread with code like this:

std::vector<int> vec;
std::atomic<bool> data_ready{false};
std::thread th([&data_ready, &vec]() {
   //we get data
   vec.push_back(something);
   data_ready = true;
});
draw_progress_dialog();
while (!data_ready) {
  process_not_user_events();
  sleep_a_little();
}
//is it here safe to use vec?

As you see I not protect "vec" by any kind of lock, but I not use "vec" in two thread at the same moment, the only problem is memory access reodering,

Is it impossible according to C++11 standard that some modifications in "vec" happens after "data_ready = true;"?

It is not clear (for me) from documentation, is it memory ordering relevant only for other atomics, or not.

Plus question, is "default" memory order is what I want, or have to change memory model?

1

There are 1 answers

1
Voo On BEST ANSWER

As long as your used memory order is at least acquire/release (which is the default), you are guaranteed to see all updates (not just the ones to atomic variables) the writing thread did before setting the flag to true as soon as you can read the write.

So yes, this is fine.