• 线程安全的单例


    自己用两种方式实现了一遍线程安全的单例,第一种方式使用了线程锁:

    #include <iostream>
    #include <thread>
    #include <mutex>
    
    class Singleton {
    public:
        Singleton(){ std::cout << " Singleton Constructor" << std::endl;};
        Singleton(const Singleton& obj) {
            ptr_ = obj.getInstance();
        }
        Singleton& operator = (const Singleton& obj) {
            if (this == &obj) {
                return *this;
            }
            ptr_ = obj.getInstance();
            return *this;
        }
        ~Singleton(){
            std::cout << "Singleton Destuctor" << std::endl;
        }
    
    
        static Singleton* getInstance() {
            std::cout << "get instance" << std::endl;
            if (ptr_ == nullptr) {
                std::mutex mtx;
                if (ptr_ == nullptr) {
                    ptr_ = new Singleton();
                } 
            }
            return ptr_;
            
        }
    
    private:
        static Singleton* ptr_;
    };
    
    Singleton* Singleton::ptr_ = nullptr;
    
    int main() {
        std::cout << "hello" << std::endl;
        Singleton* ptr = Singleton::getInstance();
        delete ptr;
    }
    

    第二种方法使用了Meyers' Singleton

    #include <iostream>
    #include <thread>
    #include <mutex>
    
    class Singleton {
    public:
        Singleton(){ std::cout << " Singleton Constructor" << std::endl;};
        Singleton(const Singleton& obj);
        Singleton& operator = (const Singleton& obj);
        ~Singleton(){
            std::cout << "Singleton Destuctor" << std::endl;
        }
    
    
        static Singleton& getInstance() {
            static Singleton instance;
            return instance;
        }
    
        void print() {
            std::cout << "do somethins" << std::endl;
        }
    };
    
    
    int main() {
        std::cout << "hello" << std::endl;
        Singleton::getInstance().print();
    }
    

      

      

  • 相关阅读:
    CodeForces
    Codeforces 1523D Love-Hate(随机化算法,sos dp)
    CodeForces
    讲题泛做
    CF vp 新题乱做
    10.11 牛客
    10.6 牛客
    10.4 牛客
    10.9 模拟考试 题解报告
    9.18 校内模拟赛 题解报告
  • 原文地址:https://www.cnblogs.com/rulin/p/14045706.html
Copyright © 2020-2023  润新知