懒汉式--------局部静态变量
class single{
public:
static single* getinstance();
private:
static pthread_mutex_t lock;
single(){
pthread_mutex_init(&lock, NULL);
}
~single(){}
}
pthread_mutex_t single::lock;
single* single::getinstance()
{
pthread_mutex_lock(&lock);
static single instance;
pthread_mutex_unlock(&lock);
return &instance;
}
懒汉式的—双重判空
class single{
public:
static single* getinstance();
private:
static pthread_mutex_t lock;
single(){
pthread_mutex_init(&lock, NULL);
}
~single(){}
static single* p;
}
pthread_mutex_t single::lock;
single* single::p;
single* single::getinstance()
{
if(NULL == p){
pthread_mutex_lock(&lock);
if(NULL == p){
p = new single;
}
}
pthread_mutex_unlock(&lock);
return p;
}
饿汉式
class single{
public:
static single* getinstance();
private:
single(){}
~single(){}
static single* p;
}
single* single::p = new single;
single* single::getinstance()
{
return p;
}