#include <iostream>
#include <atomic>
#include <mutex>
using namespace std;
class Foo {
public:
static Foo* Instance();
private:
Foo() {init();}
void init() { cout << "init done." << endl;} // your init cache function.
static atomic<Foo*> pinstance;
static mutex m_;
};
atomic<Foo*> Foo::pinstance { nullptr };
std::mutex Foo::m_;
Foo* Foo::Instance() {
if(pinstance == nullptr) {
lock_guard<mutex> lock(m_);
if(pinstance == nullptr) {
pinstance = new Foo();
}
}
return pinstance;
}
int main() {
Foo* foo1 = Foo::Instance();
Foo* foo2 = Foo::Instance();
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8YXRvbWljPgojaW5jbHVkZSA8bXV0ZXg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgpjbGFzcyBGb28gewpwdWJsaWM6CglzdGF0aWMgRm9vKiBJbnN0YW5jZSgpOwpwcml2YXRlOgoJRm9vKCkge2luaXQoKTt9Cgl2b2lkIGluaXQoKSB7IGNvdXQgPDwgImluaXQgZG9uZS4iIDw8IGVuZGw7fSAvLyB5b3VyIGluaXQgY2FjaGUgZnVuY3Rpb24uCglzdGF0aWMgYXRvbWljPEZvbyo+IHBpbnN0YW5jZTsKCXN0YXRpYyBtdXRleCBtXzsKfTsKCmF0b21pYzxGb28qPiBGb286OnBpbnN0YW5jZSB7IG51bGxwdHIgfTsKc3RkOjptdXRleCBGb286Om1fOwoKRm9vKiBGb286Okluc3RhbmNlKCkgewogIGlmKHBpbnN0YW5jZSA9PSBudWxscHRyKSB7CiAgCWxvY2tfZ3VhcmQ8bXV0ZXg+IGxvY2sobV8pOwogIAlpZihwaW5zdGFuY2UgPT0gbnVsbHB0cikgewogIAkJcGluc3RhbmNlID0gbmV3IEZvbygpOwogIAl9CiAgfQogIHJldHVybiBwaW5zdGFuY2U7Cn0KCgoKaW50IG1haW4oKSB7CglGb28qIGZvbzEgPSBGb286Okluc3RhbmNlKCk7CglGb28qIGZvbzIgPSBGb286Okluc3RhbmNlKCk7CglyZXR1cm4gMDsKfQ==