两种单例模式

双重检查锁(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;
}
相关推荐
Boop_wu2 小时前
多线程 -- 初阶(4) [单例模式 阻塞队列]
单例模式
碰大点2 天前
数据库“Driver not loaded“错误,单例模式重构方案
数据库·sql·qt·单例模式·重构
小毛驴8502 天前
软件单例模式
单例模式
ZHE|张恒3 天前
设计模式实战篇(一):彻底搞懂 Singleton 单例模式
单例模式·设计模式
Mr.wangh3 天前
单例模式&阻塞队列详解
java·开发语言·单例模式·多线程·阻塞队列
工业甲酰苯胺3 天前
TypeScript 中的单例模式
javascript·单例模式·typescript
JH30734 天前
双重检查锁定实现的单例模式,有什么问题?如何修复?
单例模式
玖剹4 天前
多线程编程:从日志到单例模式全解析
java·linux·c语言·c++·ubuntu·单例模式·策略模式
白露与泡影5 天前
面试:Spring中单例模式用的是哪种?
spring·单例模式·面试
西幻凌云5 天前
认识设计模式——单例模式
c++·单例模式·设计模式·线程安全·饿汉和懒汉