• C++实现单例模式


    单线程:

    class Singleton
    {
    private:
        static Singleton* _instance;
        Singleton()
        {
    
        }
    public:
        static Singleton* Instance()
        {
            if (nullptr == _instance)
                _instance = new Singleton();
            return _instance;
        }
        static void DestoryInstance()
        {
            if (nullptr != _instance)
            {
                delete _instance;
                _instance = nullptr;
            }
        }
        void fun()
        {
            cout << "fun" << endl;
        }
    };
    
    Singleton* Singleton::_instance = nullptr;

    C++11多线程:

    class Singleton
    {
    private:
        Singleton()
        {
    
        }
    public:
        static Singleton* Instance()
        {
            static Singleton m_instance;
            return &m_instance;
        }
    
        void fun()
        {
            cout << "fun" << endl;
        }
    };

    注:C++11标准才支持线程安全的局部静态变量初始化。
    C++memory model中定义static local variable:The initialization of such a variable is defined to occur the first time control passes through its declaration; for multiple threads calling the function, this means there’s the potential for a race condition to define first.

    C++11另一种方式:

    class Singleton
    {
    private:
        static Singleton* _instance;
        static once_flag flag;
    
        Singleton()
        {
    
        }
    public:
        static Singleton* Instance()
        {
            call_once(flag, []() { _instance = new Singleton();});
            return _instance;
        }
    
        void fun()
        {
            cout << "fun" << endl;
        }
    };
    
    Singleton* Singleton::_instance = nullptr;
    once_flag Singleton::flag;
    
    
    
    int main()
    {
        vector<thread> vt;
        for (int i = 0; i < 100; ++i)
        {
            vt.push_back(thread([]() {
                Singleton* single = Singleton::Instance();
                single->fun();
            }));
        }
        for_each(vt.begin(), vt.end(), mem_fn(&thread::join));
    
        system("pause");
        return 0;
    }
  • 相关阅读:
    java学习第六天
    java学习第五天
    java学习第四天
    java学习第三天
    java学习第二天
    java学习第一天
    性能测试学习第十三天_性能测试报告编写
    性能测试学习第十二天_性能分析
    性能测试学习第十一天_Analysis
    性能测试学习第十天_controller
  • 原文地址:https://www.cnblogs.com/ggzone/p/10121250.html
Copyright © 2020-2023  润新知