fork(24) download
  1. #include <iostream>
  2. #include <atomic>
  3. #include <mutex>
  4. using namespace std;
  5.  
  6. class Foo {
  7. public:
  8. static Foo* Instance();
  9. private:
  10. Foo() {init();}
  11. void init() { cout << "init done." << endl;} // your init cache function.
  12. static atomic<Foo*> pinstance;
  13. static mutex m_;
  14. };
  15.  
  16. atomic<Foo*> Foo::pinstance { nullptr };
  17. std::mutex Foo::m_;
  18.  
  19. Foo* Foo::Instance() {
  20. if(pinstance == nullptr) {
  21. lock_guard<mutex> lock(m_);
  22. if(pinstance == nullptr) {
  23. pinstance = new Foo();
  24. }
  25. }
  26. return pinstance;
  27. }
  28.  
  29.  
  30.  
  31. int main() {
  32. Foo* foo1 = Foo::Instance();
  33. Foo* foo2 = Foo::Instance();
  34. return 0;
  35. }
Success #stdin #stdout 0s 3272KB
stdin
Standard input is empty
stdout
init done.