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?
答案 0 :(得分:2)
只要你使用的内存顺序至少是获取/释放(这是默认值),你就可以保证在将标志设置为true之前看到写入线程所做的所有更新(不仅仅是原子变量的更新)你可以尽快阅读。
是的,这很好。