单例模式——懒汉模式(C++)

//懒汉模式
//优点: 第一次使用实例对象时,创建对象
//缺点: 复杂

#include <iostream>
#include <mutex>
#include <thread>
using namespace std;

class Singleton
{
public:
	static Singleton* GetInstance()  //获取实例
	{
		if (_spInstance == nullptr)  //双检查(Double-Check),保证效率和线程安全
									 //第二个以后的线程不用检查锁,提高效率
		{
			_smtx.lock();            //(多线程)第一个线程进来,并行的第二个线程进不来

			if (_spInstance == nullptr)
			{
				_spInstance = new Singleton;
			}

			_smtx.unlock();
		}

		return _spInstance;
	}

	// 实现一个内嵌垃圾回收类     
	class CGarbo
	{
	public:
		~CGarbo() {
			if (_spInstance)
			{
				delete _spInstance;
			}
		}
	};

private:
	Singleton()
	{
		cout << "Singleton()" << endl;
	}

	~Singleton()     //调CGarbo类的析构
	{
		cout << "~Singleton()" << endl;
	}

	//防拷贝
	Singleton(const Singleton&) = delete;
	Singleton& operator=(const Singleton&) = delete;

	static Singleton* _spInstance;  //单例对象指针
	static mutex _smtx;             //互斥锁

	static CGarbo _scg;
};

Singleton* Singleton::_spInstance = nullptr;
mutex Singleton::_smtx;

Singleton::CGarbo Singleton::_scg;

//测试多线程
void func()
{
	//Singleton::GetInstance();                 //若不加锁,会丢掉第一个线程的返回值
	cout << Singleton::GetInstance() << endl;   //测试一下
}

int main()
{
	//多线程,两个线程并行去调func函数(用来测试)
	thread t1(func); 
	thread t2(func);

	//线程等待
	t1.join();
	t2.join();

	cout << Singleton::GetInstance() << endl;
	cout << Singleton::GetInstance() << endl;


	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值