单例模式,保证一个类仅有一个实例,并提供一个访问它的全局节点。需要注意,如果是多线程,可能会出现同时访问Singleton的情况,造成创建多个实例,为了防止出现这种情况,我们需要加锁。
下面我们就简单模拟一个多线程情况下的单例模式,代码如下:
#include <stdio.h>
#include <mutex>
#include <thread>
class Singleton
{
public:
static Singleton* getinstance()
{
if (m_single==nullptr){//双重锁定,不用每次都加锁
m_mutex->lock();
if (m_single == nullptr){
m_single = new Singleton();
}
m_mutex->unlock();
}
return m_single;
}
~Singleton()
{
if (m_mutex != nullptr){
delete m_mutex;
}
}
private:
Singleton()//显示构造,防止外部 new
{
printf("使用静态函数初始化\n");
}
private:
static Singleton * m_single ;
static std::mutex* m_mutex;
};
Singleton* Singleton::m_single = nullptr;
std::mutex* Singleton::m_mutex = new std::mutex;
void threadfunc(Singleton**ppSingle)
{
*ppSingle = Singleton::getinstance();
}
int main()
{
Singleton* s1 = nullptr;
Singleton* s2 = nullptr;
std::thread first(threadfunc,&s1);
std::thread second(threadfunc,&s2);
if (nullptr != s1){
printf("%0x\n", s1);
if (s1 == s2){
printf("两个对象是同一个实例\n");
}
}
first.join();
second.join();
return 0;
}