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

来源:互联网 发布:淘宝3d试衣技术 编辑:程序博客网 时间:2020/10/22 23:32
//文章参见: 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;