学习如何用 C++ 写一个线程安全的单例模式

参考书籍:《C++ 设计模式》李阳阳

cpp 复制代码
#pragma once
#inlcude <iostream>
using namespace std;
#include <mutex>

struct lugard_sync {
    explicit lugard_sync(std::mutex &_mutex) : m_mutex(_mutex) {
        m_mutex.lock();
    }
	
	~lugard_sync() { m_mutex.unlock(); }

private:
    std::mutex &m_mutex;
}

class Monitor {
private: 
    // 注意点 1:单例类的构造函数是私有的,这样能够保证
    //           外部类无法调用该构造函数来生成多个实例
    Monitor() {}
    
    // 注意点 2:为避免类在外部实例化,该类自身必须定义
    //           一个静态私有实例
    static Monitor *instance;

public:
    // 注意点 3:向外提供一个静态的公有函数,用于创建或
    //           获取该静态私有实例
    static Monitor* get_instance() {
        std::mutex mt;
        lugard_sync(mt);
        if (instance == nullptr) {
            instance = new Monitor();
        }
        return instance;
    }
相关推荐
CoderYanger1 天前
动态规划算法-子数组、子串系列(数组中连续的一段):21.乘积最大子数组
开发语言·算法·leetcode·职场和发展·动态规划·1024程序员节
CoderYanger1 天前
A.每日一题——3432. 统计元素和差值为偶数的分区方案
java·数据结构·算法·leetcode·1024程序员节
CoderYanger1 天前
动态规划算法-子数组、子串系列(数组中连续的一段):26.环绕字符串中唯一的子字符串
java·算法·leetcode·动态规划·1024程序员节
韩家阿杰2 天前
RabbitMQ技术的使用
1024程序员节
CoderYanger3 天前
动态规划算法-简单多状态dp问题:15.买卖股票的最佳时机含冷冻期
开发语言·算法·leetcode·动态规划·1024程序员节
CoderYanger3 天前
递归、搜索与回溯-FloodFill:33.太平洋大西洋水流问题
java·算法·leetcode·1024程序员节
CoderYanger3 天前
动态规划算法-斐波那契数列模型:2.三步问题
开发语言·算法·leetcode·面试·职场和发展·动态规划·1024程序员节
CoderYanger3 天前
动态规划算法-简单多状态dp问题:16.买卖股票的最佳时机含手续费
开发语言·算法·leetcode·动态规划·1024程序员节
CoderYanger3 天前
C.滑动窗口-求子数组个数-越短越合法——3258. 统计满足 K 约束的子字符串数量 I
java·开发语言·算法·leetcode·1024程序员节
CoderYanger3 天前
动态规划算法-路径问题:9.最小路径和
开发语言·算法·leetcode·动态规划·1024程序员节