I was asking myself if an atomic bool ready flag could ensure that a data is syncronised between thread (I have already read this Synchronization Mechanism For "data ready" Flag? ) but no comment answer to my question.
for exemple see this code :
#include<atomic>
#include<thread>
class BIG_DATA {
public:
BIG_DATA(){ std::this_thread::sleep_for(std::chrono::seconds(1)); }//some big data to init ......
};
void init_BIG_DATA(BIG_DATA* & location, std::atomic<bool>& flag ) {
if (flag.load())throw("error : data already loaded");
location = new BIG_DATA(); //heavy operation
flag.store(true);
}
class data {
public:
data() {
ready.store(false);
std::thread t = std::thread(init_BIG_DATA,std::ref(_data),std::ref(ready));
t.detach();
}
BIG_DATA* get_data() {
if (ready.load()) return _data;
else return nullptr;
}
private:
BIG_DATA* _data = nullptr;
std::atomic<bool> ready;
};
in this code if i have a main like this :
data d;
while (d.get_data() == nullptr) ; // wait for Big data to be constructed in an other thread
BIG_DATA* BD = d.get_data();
// do somethin with big data
Do I am ensured that the thing I do with the BIG_DATA* (BD) are correct and that the object is sycronised between the creator and worker thread ? Is this code thread safe ?