两种单例模式

双重检查锁(DCLP)

  • 通过 std::mutex 保证线程安全
  • 双重检查减少了锁的开销,只有第一次创建时才会加锁
cpp 复制代码
#include <iostream>
#include <mutex>

class Singleton {
private:
    static Singleton* instance;
    static std::mutex mtx;

    // 私有构造函数,禁止外部创建
    Singleton() {
        std::cout << "Constructor called\n";
    }

public:
    // 删除拷贝和赋值,防止拷贝产生多个实例
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

    static Singleton* getInstance() {
        if (instance == nullptr) { // 第一次检查
            std::lock_guard<std::mutex> lock(mtx);
            if (instance == nullptr) { // 第二次检查
                instance = new Singleton();
            }
        }
        return instance;
    }

    void show() {
        std::cout << "Singleton instance address: " << this << "\n";
    }
};

// 静态成员初始化
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;

int main() {
    Singleton* s1 = Singleton::getInstance();
    Singleton* s2 = Singleton::getInstance();

    s1->show();
    s2->show();

    return 0;
}

静态局部变量

  • C++11 标准保证静态局部变量的初始化是线程安全的
  • 不需要手动加锁
cpp 复制代码
#include <iostream>

class Singleton {
private:
    Singleton() {
        std::cout << "Constructor called\n";
    }

public:
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

    static Singleton& getInstance() {
        static Singleton instance; // C++11 保证线程安全
        return instance;
    }

    void show() {
        std::cout << "Singleton instance address: " << this << "\n";
    }
};

int main() {
    Singleton& s1 = Singleton::getInstance();
    Singleton& s2 = Singleton::getInstance();

    s1.show();
    s2.show();

    return 0;
}
相关推荐
koping_wu14 小时前
【设计模式】设计模式原则、单例模式、工厂模式、模板模式、策略模式
单例模式·设计模式·策略模式
一枝小雨2 天前
单例模式简析:C语言实现单例模式
c语言·单例模式·嵌入式
SoleMotive.3 天前
单例模式什么时候用饿汉什么时候用懒汉
单例模式
ZouZou老师4 天前
C++设计模式之单例模式:以小区快递柜为例
c++·单例模式·设计模式
繁华似锦respect4 天前
lambda表达式中的循环引用问题详解
java·开发语言·c++·单例模式·设计模式·哈希算法·散列表
别叫我->学废了->lol在线等5 天前
python单例模式下线程安全优化
python·安全·单例模式
繁华似锦respect5 天前
单例模式出现多个单例怎么确定初始化顺序?
java·开发语言·c++·单例模式·设计模式·哈希算法·散列表
while(1){yan}6 天前
JAVA单例模式
java·单例模式
Albert Edison8 天前
【项目设计】C++ 高并发内存池
数据结构·c++·单例模式·哈希算法·高并发
繁华似锦respect9 天前
HTTPS 中 TLS 协议详细过程 + 数字证书/签名深度解析
开发语言·c++·网络协议·http·单例模式·设计模式·https