pthread_once
class Singleton {
public: static Singleton *GetInstance() { pthread_once(&ponce_, &Singleton::init); return value_; } private: Singleton() {} Singleton(const Singleton &); Singleton& operator= (const Singleton &); static void init() { value_ = new T(); } static pthread_once_t ponce_; static Singleton *value_;};pthread_once_t SIngleton::ponce_ = PTHREAD_ONCE_INIT;Singleton* Singleton::value_ = NULL;---------------------饿汉模式
必须在main开始前就初始化好,于是,需要一个静态变量。可以是对象,也可以是对象的指针。如果是指针,在main开始前new一下就行。由于这个静态变量只会被单例类使用,所以最好不是静态全局变量,而是类的静态成员变量。// 对象版
// singleton.hclass Singleton { private: Singleton() {} Singleton(const Singleton &); Singleton& operator= (const Singleton &); static Singleton s; public: static Singleton *GetInstance() { return &s; }};// singleton.ccSingleton Singleton::s;还有://指针版。没有析构逻辑,会造成泄露。
// singleton.hclass Singleton { private: Singleton() {} Singleton(const Singleton &); Singleton& operator= (const Singleton &); static Singleton *p; public: static Singleton *GetInstance() { return p; }};// singleton.ccSingleton *Singleton::p = new Singleton;
class Singleton
{ private: static Singleton* m_instance; Singleton(){}public: static Singleton* getInstance();};Singleton* Singleton::getInstance()
{ if(NULL == m_instance) { Lock();//借用其它类来实现,如boost if(NULL == m_instance) { m_instance = new Singleton; } UnLock(); } return m_instance;}
====================
MasterConf* MasterConf::instance_ = NULL;
pthread_mutex_t MasterConf::mutex_ = PTHREAD_MUTEX_INITIALIZER;
MasterConf* MasterConf::GetInstance() {
if (NULL == instance_) { pthread_mutex_lock(&mutex_); if (NULL == instance_) { instance_ = new MasterConf(); } pthread_mutex_unlock(&mutex_); }return instance_;
}