muduo网络库:单例设计

来源:互联网 发布:淘宝客源码采集优惠券 编辑:程序博客网 时间:2024/05/14 22:09

相对于传统的double checkd locking(DCL),其实也是靠不住的~~
具体原因参考下面的文章:
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

陈硕的解法的利用Pthreads库中的pthread_once.
函数原型:

int pthread_once(pthread_once_t *once_control, void (*init_routine) (void));

以此来保证 init_routine()函数仅执行一次。

template<typename T>class Singleton : boost noncopyable{public:    static T& instance(){        pthread_once(&ponce_,&Singleton::init);         return *value_;    }private:    Singleton();    ~Singleton();    static void init(){        value_ = new T();    }private:    static pthread_once_t ponce_;    static T* value_;};//必须在头文件中定义static 变量 template <typename T>pthread_once_t Singleton<T> ::ponce_ = PTHREAD_ONCE_INIT;template <typename T>T* Singleton<T>::value_ = NULL; //使用Foo& foo = Singleton<Foo>::instance(); 
0 0