Atomic / non-atomic mixture, any guarantees?

Let's say I have a 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 can see, I am not protecting "vec" from any kind of blocking, but I am not using "vec" in two threads at the same moment, the only problem is relocation of memory access,

Is it not possible according to the C ++ 11 standard some changes to "vec" to happen after "data_ready = true"?

It's not clear (to me) from the documentation if this is a memory ordering that only applies to other atoms or not.

Plus the question is, is "default memory" the memory order that I want, or do I need to change the memory model?

+3


source to share


1 answer


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



So yes, that's okay.

+2


source







All Articles