c++设计模式-单例模式

单例模式:

单例模式一般会分为:饿汉单例和懒汉单例

饿汉式: 在类加载的时候就完成初始化,所以类加载比较慢,但是获取对象的速度是比较快的.
懒汉式:在类加载的时候不初始化,等到第一次被使用的时候才进行初始化.

饿汉式:

class Singlenton{
	private:
		Singlenton() = default;
	    ~Singlenton() = default;
	 public:
	 	static  Singlenton & getInstance();
};
Singlenton &  Singlenton::getInstance(){
		static Singlenton c;
		return c;
}

饿汉式:

class Singlenton{
    private:
        Singlenton();
        Singlenton(const Singlenton &);
    public:
    static Singlenton * getInstance();
    static Singlenton* m_instance;
};

Singlenton * Singlenton::m_instance = nullptr;

Singlenton* Singlenton::getInstance() {
    if(m_instance == nullptr){
        m_instance = new Singlenton();
    }
    return m_instance;
}

这种方案对于多线程模式并不是安全的,有可能会同时创建多个对象
那么,我们肯定会随之进行加锁操作,但是在这里的话锁的代价过高

Singlenton* Singlenton::getInstance() {
 std::lock_guard<mutex> b(mutex_);
    if(m_instance == nullptr){
        m_instance = new Singlenton();
    }
    return m_instance;
    }

线程A没有释放锁,B无法进入,第一次之后,相当于多个线程仅仅是对这个地方进行读取,而对于多线程读的话是没有必要进行加锁,对于高并发的情况下,代价及其高昂
在这里我们可以使用双检查锁

Singlenton* Singlenton::getInstance() {
 if(m_instance == nullptr){
 //在执行这一行之前,有可能多个线程同时都执行到这一步
 std::lock_guard<mutex> b(mutex_);
    if(m_instance == nullptr){
        m_instance = new Singlenton();
    }
    }
    return m_instance;
    }

//消除代价过高的问题,对于上一次的缺陷进行完善
但是仍然有问题,内存读写reorder可能会造成不安全的情况
线程是在指令层级进行时间片的抢夺,cpu执行指令可能并不如我们之前的预期情况执行

std::atomic<Singlenton*> Singlenton::m_instance;
Singlenton* Singlenton::getInstance() {
	Singleton * temp = m_instance.load(std::memory_order_relaxed);
	//只保证在同一个线程内,同一个原子变量的操作的执行序列不会被重排序(reorder),这种保证也称之为modification order consistency,但是其他线程看到的这些操作的执行序列式不同的。
	std::atomic_thread_fence(std::memory_order_acquire); //获取内存的fence获取存储
 if(temp == nullptr){
 //在执行这一行之前,有可能多个线程同时都执行到这一步
 std::lock_guard<mutex> b(mutex_);
    if(temp== nullptr){
       temp = new Singlenton();
       std::atomic_thread_fence(std::memory_order_release); //释放内存fence
       m_instance.store(temp,std::memory_order_relaxed);
    }
    }
    return m_instance;
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值