线程安全的单例

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

#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();
}

  

  

原文地址:https://www.cnblogs.com/rulin/p/14045706.html