线程安全的C++的Singleton实现

//文章参见: http://www.2maomao.com/blog/when-cplusplus-meet-singleton/

//------------------Implementation #1 ----------------------
//s.h

class Singleton {
  private:
    Singleton();
    static Singleton* instance_;
  public:
    static Singleton* getInstance() {
        if (!instance_)
            instance_ = new Singleton();
        return instance_} };

//s.cpp
Singleton* Singleton::pInstance_ = 0;


//------------------Implementation #2 ----------------------
//s.h

class Singleton {
  private:
    Singleton();
  public:
    static Singleton* getInstance() {
        static Singleton* instance_ = new Singleton();
        return instance_} };


//------------------Implementation #1.1 ----------------------
//s.h

class Singleton {
  private:
    Singleton();
    static Singleton* instance_;
  public:
    static Singleton* getInstance() {
        lock_mutex();
        if (!instance_)
            instance_ = new Singleton();
        unlock_mutex();
        return instance_} };

//s.cpp
Singleton* Singleton::pInstance_ = 0;

//------------------Implementation #1.2 ----------------------
//s.h

class Singleton {
  private:
    Singleton();
    static Singleton* instance_;
  public:
    static Singleton* getInstance() {
        if (!instance_{
          lock_mutex();
          if (!instance_)
              instance_ = new Singleton();
          unlock_mutex();}
        return instance_} };

//s.cpp
Singleton* Singleton::pInstance_ = 0;


//------------------Implementation #1.3 ----------------------
//s.h

class Singleton {
  private:
    Singleton();
    static Singleton* instance_;
    static int flag_;
  public:
    static Singleton* getInstance() {
        if (!flag_{
          lock_mutex();
          if (!instance_)
              instance_ = new Singleton();
          unlock_mutex();}
          flag_ = 1;
        return instance_} };

//s.cpp
Singleton* Singleton::pInstance_ = 0;
Singleton* Singleton::flag_ = 0;

你可能感兴趣的:(线程安全的C++的Singleton实现)