设计模式

class singleton{
  private:
 static volatile singleton* p;
 static pthread_mutex_t mtx;
 singleton(){}
 
  public:
  singleton* getInstance();
}
 singleton*singleton::p=NULL;
 pthread_mutex_t singleton::mtx;
 singleton* singleton::getInstance(){
  if(p==NULL){
  pthread_mutex_lock (&mtx);
  if(p==NULL) p=new singleton;
  pthread_mutex_unlock(&mtx);
 }
return p;
}

以上是懒汉模式,为了线程安全,需要两次判断

还有饿汉模式

posted on 2017-09-12 23:33  zhaodun  阅读(116)  评论(0编辑  收藏  举报

导航