关于单例模式的定义以及其最基本的实现不再多提,需要指出的是,对于一般的单例模式,仅凭 if(hold_ == NULL) 这类语句来进行判断显然很难达到线程安全的要求,因此本文通过pthread_once 来实现。
注意,也可以通过线程同步机制,例如锁,信号量等形式来实现。
template<typename T> class Signleton: boost noncopyable{ public: static T& instance(){ pthead_once(&ponce_, &Signleton::init); return *value_; } private: // 将构造和析构函数设置为private, 使单例模式不能在栈上创建 Signleton(); ~Signleton(); static void init(){ value_ = new T(); } private: static pthread_once_t ponce_; static T* value_; // 单例模式中的数据 }; // 必须在头文件中定义static 变量 pthread_once_t Signleton<T>::ponce_ = PTHREAD_ONCE_INIT; template<typename T> T* Signleton<T>::value_ NULL;这个单例模式并没有考虑如何销毁对象。