C++单例模式以及线程安全

写一个单例模式:

class MySingleton
{
public:
      static MySingleton * GetInstance()
      //static method that returns only instance of MySingletone
      {
            if (m_pOnlyOneInstance == NULL) // if not yet instantiated
            {
                  m_pOnlyOneInstance = new MySingleton();
                  //create one and only object
            }

            return m_pOnlyOneInstance;
      }

private:

      static MySingleton * m_pOnlyOneInstance;
      //holds one and only object of MySingleton

      MySingleton(); // private constructor

public:
      // MySingleton functionalities
      void foo();
      bool goo();
      int zoo();
};

临界区实现线程安全:

MySingleton * GetInstance() //usage of critcal section makes it thread safe
{
      EnterCriticalSection();
      //other client threads, if any, now have to wait till current
      // thread leaves critical section. Forget semantics and
      // compilation for Crit Section, and treat this as pseudo-code
      if (m_pOnlyOneInstance == NULL)
      {
          m_pOnlyOneInstance = new MySingleton();
      }

      LeaveCriticalSection();

      return m_pOnlyOneInstance;
}

互斥量实现线程安全(boost):

#ifndef SINGLETON_H_
#define SINGLETON_H_

#include 
#include 

template<class T>
class Singleton
{
public:
  static T& GetInstance()
  {
    assert(!is_destructed);
    (void)is_destructed; // prevent removing is_destructed in Release configuration

    boost::mutex::scoped_lock lock(GetMutex());
    static T instance;
    return instance;
  }

private:
  static bool is_destructed;

  static boost::mutex& GetMutex()
  {
    static boost::mutex mutex;
    return mutex;
  }

  Singleton() {}
  ~Singleton() { is_destructed = true; }
};

// force creating mutex before main() is called
template<class T>
bool Singleton::is_destructed = (Singleton::GetMutex(), false);

#endif // SINGLETON_H_

互斥量实现线程安全(c++11):

#include 
#include 
#include 
using namespace std;

class Foo {
public:
    static Foo* Instance();
private:
    Foo() {init();}
    void init() { cout << "init done." << endl;} // your init cache function.
    static atomic pinstance;
    static mutex m_;
};

atomic Foo::pinstance { nullptr };
std::mutex Foo::m_;

Foo* Foo::Instance() {
  if(pinstance == nullptr) {
    lock_guard lock(m_);
    if(pinstance == nullptr) {
        pinstance = new Foo();
    }
  }
  return pinstance;
}



int main() {
    Foo* foo1 = Foo::Instance();
    Foo* foo2 = Foo::Instance();
    return 0;
}

std::call_once() 智能指针实现线程安全:

#include 
#include 

class CSingleton
{
public:
    virtual ~CSingleton();
    static CSingleton& GetInstance();

private:
    static std::unique_ptr m_instance;
    static std::once_flag m_onceFlag;
    CSingleton(void);
    CSingleton(const CSingleton& src);
    CSingleton& operator=(const CSingleton& rhs);
};

std::unique_ptr CSingleton::m_instance;
std::once_flag CSingleton::m_onceFlag;

CSingleton& CSingleton::GetInstance()
{
    std::call_once(m_onceFlag,
        [] {
            m_instance.reset(new CSingleton);
    });
    return *m_instance.get();
}

你可能感兴趣的:(C++)