/**
* @brief C++线程安全的单例模式
*/
#include <iostream>
#include <mutex>
class Singleton
{
private:
///构造析构定义为私有,防止外部实例化对象
Singleton() { std::cout << "Singleton construct" << std::endl; }
~Singleton() { std::cout << "Singleton destruct" << std::endl; }
private:
///静态私有实例指针,维持单实例
static Singleton* _instance;
///静态私有互斥量,多线程安全
static std::mutex _mutex;
private:
///嵌套类负责在程序推出时自动析构实例
class Nest
{
public:
~Nest()
{
if (_instance)
{
delete _instance;
_instance = NULL;
}
}
};
public:
///静态公有函数负责向外部提供实例指针
static Singleton* createInstance()
{
///双重验证,既能实现线程安全,又能最小化性能消耗
if (NULL == _instance)
{
std::unique_lock<std::mutex>lock(_mutex);
if (NULL == _instance)
{
_instance = new Singleton;
///静态局部对象,可以在程序退出时自动析构实例
static Singleton::Nest _nest;
}
}
return _instance;
}
///测试函数
void doSomething()
{
std::cout << "doSomething" << std::endl;
}
};
///静态成员变量在类外初始化
/*static*/Singleton* Singleton::_instance = NULL;
/*static*/std::mutex Singleton::_mutex;
void threadFun()
{
Singleton* t = Singleton::createInstance();
t->doSomething();
}
int main()
{
std::thread t1(threadFun);
std::thread t2(threadFun);
t1.join();
t2.join();
getchar();
return 0;
}