首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

pthread_once重塑singleton方式

2013-11-01 
pthread_once重塑singleton模式单件模式是非线程安全的:#includeiostream#includepthread.h#includeu

pthread_once重塑singleton模式

单件模式是非线程安全的:

#include<iostream>#include<pthread.h>#include<unistd.h>#include<stdlib.h>#include<boost/noncopyable.hpp>using namespace std;using namespace boost;template<typename T>class singleton:noncopyable{    public:        static T& instance(){            pthread_once(&ponce,&singleton::init);//第一次调用才会执行init,此后将改变ponce并将已经执行记录存入ponce            return *value;        }    private:        singleton();        ~singleton();        static void init(){            value=new T();//这里只能调用T的默认构造函数,若要用户指定T的构造方式,可能需要模板特化...不怎么熟悉...汗        }    private:        static pthread_once_t ponce;        static T* value;};template<typename T>//静态成员类外初始化pthread_once_t singleton<T>::ponce=PTHREAD_ONCE_INIT;//ponce初始化template<typename T>T* singleton<T>::value=NULL;class test{//测试对象    public:        void show(){            cout<<"show()"<<endl;        }};int main(){    test& p=singleton<test>::instance();//注意使用方法    p.show();    test& q=singleton<test>::instance();    if(&p==&q)        cout<<"singleton success"<<endl;    else        cout<<"singleton failure"<<endl;    return 0;}


程序输出:
show()
singleton success

热点排行