两种单例模式

双重检查锁(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;
}
相关推荐
重生之我是Java开发战士9 天前
【Java SE】多线程(三):单例模式,阻塞队列,线程池与定时器
java·javascript·单例模式
许彰午10 天前
34_Java设计模式之单例模式
java·单例模式·设计模式
罗超驿12 天前
10.Java单例模式全解析:饿汉式与懒汉式实现及线程安全深度剖析
安全·单例模式·javaee
布朗克16812 天前
33 设计模式精讲
java·单例模式·设计模式
雨浓YN12 天前
基于设计模式的Winform软件框架-01Xml\Log\Ini日志(单例模式+生产者消费者模式)
单例模式·设计模式
仙俊红13 天前
Java 单例模式:类里面为什么可以有自己类型的字段?
java·开发语言·单例模式
swordbob13 天前
prototype 注入到 singleton 里,prototype是否还是线程安全的
安全·spring·单例模式·原型模式
谁似人间西林客14 天前
工业大数据实战:看中国智造如何用数据驱动效率革命
大数据·单例模式
张小姐的猫15 天前
【Linux】多线程 —— 线程池 | 单例模式 | 常见锁
linux·运维·服务器·c++·单例模式·设计模式·策略模式
Java面试题总结16 天前
双重检验锁的单例模式在高并发下的可见性问题
单例模式