设计模式C++版:第十一式单例模式

单例模式,保证一个类仅有一个实例,并提供一个访问它的全局节点。需要注意,如果是多线程,可能会出现同时访问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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值