1、饿汉式单例类
#ifndef EAGER_SINGLETON_H
#define EAGER_SINGLETON_H
#include <iostream>
#include <pthread.h>
class EagerSingleton
{
public:
~EagerSingleton() {
delete instance_;
}
static EagerSingleton* getSingletonInstance() {
return instance_;
}
unsigned add() {
unsigned tmp(0);
pthread_mutex_lock(&mutex_);
count++;
tmp = count;
pthread_mutex_unlock(&mutex_);
return tmp;
}
private:
EagerSingleton(){
std::cout << "call constructor" << std::endl;
count = 0;
}
unsigned count;
static pthread_mutex_t mutex_;
static EagerSingleton* instance_;
};
EagerSingleton* EagerSingleton::instance_ = new EagerSingleton;//类加载时初始化,确保唯一性
pthread_mutex_t EagerSingleton::mutex_ = PTHREAD_MUTEX_INITIALIZER;
#endif
#include "EagerSingleton.h"
#include <pthread.h>
#include <unistd.h>
#include <iostream>
void* run(void *arg)
{
int *id = static_cast<int*>(arg);
EagerSingleton* p = EagerSingleton::getSingletonInstance();
std::cout << *id << "\t" << pthread_self() << "\t" << p << "\t" << p->add() << std::endl;
}
void test()
{
for (int i = 0; i < 10; ++i) {
pthread_t tid;
pthread_create(&tid, NULL, run, static_cast<void*>(&i));
}
}
int main()
{
test();
return 0;
}
测试结果:
2、懒汉式单例类
#ifndef LAZY_SINGLETON_H
#define LAZY_SINGLETON_H
#include <iostream>
#include <pthread.h>
//懒汉式,延迟加载(Lazy Load)技术
class LazySingleton
{
public:
~LazySingleton() {
if (instance_)
delete instance_;
}
//双重检查锁定(Double-Check Locking)
static LazySingleton* getSingletonInstance() {
if (instance_ == NULL) {
pthread_mutex_lock(&mutex_);
if (instance_ == NULL) {
instance_ = new LazySingleton;
}
pthread_mutex_unlock(&mutex_);
}
return instance_;
}
unsigned add() {
unsigned tmp(0);
pthread_mutex_lock(&mutex_);
count++;
tmp = count;
pthread_mutex_unlock(&mutex_);
return tmp;
}
private:
LazySingleton() {
std::cout << "call constructor" << std::endl;
count = 0;
}
unsigned count;
static pthread_mutex_t mutex_;
static LazySingleton* instance_;
};
LazySingleton* LazySingleton::instance_ = NULL;
pthread_mutex_t LazySingleton::mutex_ = PTHREAD_MUTEX_INITIALIZER;
#endif
#include "LazySingleton.h"
#include <pthread.h>
#include <unistd.h>
#include <iostream>
void* run(void *arg)
{
LazySingleton *p = NULL;
do{
p = LazySingleton::getSingletonInstance();
usleep(100000);
} while(p == NULL);
std::cout << pthread_self() << "\t" << p << "\t" << p->add() << std::endl;
}
void test()
{
for (int i = 0; i < 10; ++i) {
pthread_t tid;
pthread_create(&tid, NULL, run, NULL);
}
}
int main()
{
test();
sleep(1000);
return 0;
}
参考:
《设计模式的艺术——软件开发人员内功修炼之道》 刘伟 著