在生成单例时加锁,生成结束后释放锁。
注意两点:volatile 和 double-check
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
class singleton{
private:
static volatile singleton *p;
static pthread_mutex_t mtx;
singleton(){}
public:
static 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;
}
int main(){
singleton * ptr = singleton::getInstance();
singleton * ptr1 = singleton::getInstance();
return 0;
}
网友评论