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


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

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

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

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

        1.使用静态互斥量

         

    #include

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

            if (!pSingleModeSecure)
            {
                std::lock_guard 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() { }    
    };

  • 相关阅读:
    在线负载离线负载与在线算法离线算法
    Fritzing软件绘制Arduino面包板接线图传感器模块库文件223
    事件循环的学习、执行上文、this、执行栈和任务队列
    TypeScript 基本语法
    解析java中的文件字节输出流
    网络安全还有就业前景吗?转行网络安全可行吗?
    web前-JAVA后端 数据API接口交互协议
    Mysql查询训练——50道题
    PMP项目管理中的重要角色
    新手如何去做性能测试?
  • 原文地址:https://blog.csdn.net/face_to/article/details/126604377