设计模式

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;
}

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

还有饿汉模式

原文地址:https://www.cnblogs.com/zhaodun/p/7512844.html