Just want to know whether atomic_flag = 1;
keeps the myclass_st assignment thread-safe or not. (I am sorry that my example has so many problems, so I have changed it.)
myClass* myclass_st = nullptr;
std::atomic<int> atomic_flag;
std::mutex mtx; //err
myClass* get_instance() {
//std::unique_lock<std::mutex> lk(mtx);
if (myclass_st == nullptr) {
mtx.lock();
if (myclass_st == nullptr) {
myclass_st = new myClass();
atomic_flag = 1;
mtx.unlock(); //err
}
}
return myclass_st;
}
I know we can use static
after c11.
Maybe I should modify the code like this ?
myClass* myclass_st = nullptr;
std::atomic<int> atomic_flag;
myClass* get_instance() {
if (atomic_flag.load() == 0) {
std::unique_guard<std::mutex> lk(mtx);
if (atomic_flag.load() == 0) {
myclass_st = new myClass();
atomic_flag = 1;
}
}
return myclass_st;
}