本文总结自李建忠老师的设计模式课程
class Singleton{
private:
Singleton();
Singleton(const Singleton& other);
public:
static Singleton* getInstance();
static Singleton* m_instance;
};
Singleton* Singleton::m_instance=nullptr;
//(1)线程非安全版本
Singleton* Singleton::getInstance() {
if (m_instance == nullptr) {
m_instance = new Singleton();
}
return m_instance;
}
//(2)线程安全版本,但锁的代价过高
Singleton* Singleton::getInstance() {
Lock lock;
if (m_instance == nullptr) {
m_instance = new Singleton();
}
return m_instance;
}
//(3)双检查锁,但由于内存读写reorder不安全
Singleton* Singleton::getInstance() {
if(m_instance==nullptr){//只有在m_instance空时再加锁
Lock lock;
if (m_instance == nullptr) {//若不加第二次判断,线程A,B都能够执行new
m_instance = new Singleton();//我们假定的顺序先分配内存,再调用构造器,再返回指针
//(reorder:)但可能实际上是,先分配内存,然后直接把分配的内存给m_instance(此时如果另一个线程进入第一层判断,m_instance不是 //nullptr直接返回了一个没有构造完成的m_instance),再调用构造器
}
}
return m_instance;
}
//(4)C++ 11版本之后的跨平台实现 (volatile),
std::atomic<Singleton*> Singleton::m_instance;
std::mutex Singleton::m_mutex;
Singleton* Singleton::getInstance() {
Singleton* tmp = m_instance.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);//获取内存fence,让编译器不再优化
if (tmp == nullptr) {
std::lock_guard<std::mutex> lock(m_mutex);
tmp = m_instance.load(std::memory_order_relaxed);
if (tmp == nullptr) {
tmp = new Singleton;
std::atomic_thread_fence(std::memory_order_release);//释放内存fence
m_instance.store(tmp, std::memory_order_relaxed);
}
}
return tmp;
}
单例大约有两种实现方法:懒汉与饿汉。
* 懒汉:故名思义,不到万不得已就不会去实例化类,也就是说在第一次用到类实例的时候才会去实例化,所以上边的经典方法被归为懒汉实现; * 饿汉:饿了肯定要饥不择食。所以在单例类定义的时候就进行实例化。
特点与选择:
* 由于要进行线程同步,所以在访问量比较大,或者可能访问的线程比较多时,采用饿汉实现,可以实现更好的性能。这是以空间换时间。 *
在访问量较小时,采用懒汉实现。这是以时间换空间。
//饿汉式
class singleton
{
protected:
singleton() {}
private:
static singleton* p;
public:
static singleton* initance();
};
singleton* singleton::p = new singleton;
Singleton::m_instance = nullptr;
singleton* singleton::initance()
{
return p;
}
利用pthread_once实现
template<typename T>
class Singleton : boost::noncopyable
{
public:
static T& instance()
{
pthread_once(&ponce_,&Singleton::init);
return *value;
}
private:
Singleton();
~Singleton();
static void init()
{
value_ = new T();
}
private:
static pthread_once_t ponce_;
static T* value_;
};
//必须在头文件中定义 static变量
template<typename T>
pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT;
template<typename T>
T* Singleton<T>::value_ = NULL;