c++单例模式线程安全几种实现方式

    c++编程中,单例模式经常用到,单例模式有懒汉模式和饿汉模式两种。

    懒汉模式直接采用静态变量,但是占用内存。

    饿汉模式,根据需要动态生成,但是多个线程同时调用,存在线程安全问题。

    下面主要总结饿汉模式中几种线程安全写法:

    1.使用静态互斥量

     

#include<mutex>

class SingleModeSecure 
{
public:
    ~SingleModeSecure() {}
    
    static SingleModeSecure* Instance(void)
    {
        static SingleModeSecure* pSingleModeSecure = nullptr;
        static std::mutex  sMutex;

        if (!pSingleModeSecure)
        {
            std::lock_guard<std::mutex> lock(sMutex);
            if (nullptr == pSingleModeSecure)
            {
                pSingleModeSecure = new SingleModeSecure();
            }
        }
        
        return pSingleModeSecure;
    }

protected:

private:
    SingleModeSecure() { }

};

2.使用std::call_once创建单例模式

class SingleModeSecure2
{
public:
    ~SingleModeSecure2() {}
    
    static SingleModeSecure2* Instance(void)
    {
        static SingleModeSecure2* pSingleModeSecure2 = nullptr;
        static std::once_flag one_flag;
        std::call_once(one_flag, []() {        
                       std::cout << "call once" << std::endl;
                       pSingleModeSecure2 = new SingleModeSecure2(); });
        return pSingleModeSecure2;
    }

    void Out(void) {}
    //
    
protected:

private:
    SingleModeSecure2() { }    
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值