C++线程安全的单例模式

/**
 * @brief C++线程安全的单例模式
 */

#include <iostream>
#include <mutex>

class Singleton
{
private:
    ///构造析构定义为私有,防止外部实例化对象
    Singleton() { std::cout << "Singleton construct" << std::endl; }
    ~Singleton() { std::cout << "Singleton destruct" << std::endl; }

private:
    ///静态私有实例指针,维持单实例
    static Singleton* _instance;
    ///静态私有互斥量,多线程安全
    static std::mutex _mutex;

private:
    ///嵌套类负责在程序推出时自动析构实例
    class Nest
    {
    public:
        ~Nest()
        {
            if (_instance)
            {
                delete _instance;
                _instance = NULL;
            }
        }
    };

public:
    ///静态公有函数负责向外部提供实例指针
    static Singleton* createInstance()
    {
        ///双重验证,既能实现线程安全,又能最小化性能消耗
        if (NULL == _instance)
        {
            std::unique_lock<std::mutex>lock(_mutex);
            if (NULL == _instance)
            {
                _instance = new Singleton;
                ///静态局部对象,可以在程序退出时自动析构实例
                static Singleton::Nest _nest;
            }
        }
        return _instance;
    }
    ///测试函数
    void doSomething()
    {
        std::cout << "doSomething" << std::endl;
    }
};

///静态成员变量在类外初始化
/*static*/Singleton* Singleton::_instance = NULL;
/*static*/std::mutex Singleton::_mutex;

void threadFun()
{
    Singleton* t = Singleton::createInstance();
    t->doSomething();
}

int main()
{
    std::thread t1(threadFun);
    std::thread t2(threadFun);
    t1.join();
    t2.join();

    getchar();
    return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值