您当前的位置: 首页 >  安全

惊鸿一博

暂无认证

  • 7浏览

    0关注

    535博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

设计模式_单例模式回顾_C++版不使用锁保证多线程安全

惊鸿一博 发布时间:2021-01-03 18:08:55 ,浏览量:7

最推荐的懒汉式单例(magic static )——局部静态变量 说明:

这种方法又叫做 Meyers' SingletonMeyer's的单例, 是著名的写出《Effective C++》系列书籍的作者 Meyers 提出的。所用到的特性是在C++11标准中的Magic Static特性:

If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.如果当变量在初始化的时候,并发同时进入声明语句,并发线程将会阻塞等待初始化结束。

这样保证了并发线程在获取静态局部变量的时候一定是初始化过的,所以具有线程安全性。

C++静态变量的生存期 是从声明到程序结束,这也是一种懒汉式。

这是最推荐的一种单例实现方式:

  1. 通过局部静态变量的特性保证了线程安全 (C++11, GCC > 4.3, VS2015支持该特性);
  2. 不需要使用共享指针,代码简洁;
  3. 注意在使用的时候需要声明单例的引用 Single& 才能获取对象。
代码:
#include 

class Singleton
{
private:
    Singleton(){//cout}
public:
    Singleton(const Singleton&)=delete;
    Singleton& operator=(const Singleton&)=delete;
    
    static Singleton& get_instance(){
        static Singleton instance;
        return instance;
    }
    ~Singleton(){//cout}
};

参考:C++ 单例模式总结与剖析

关注
打赏
1663399408
查看更多评论
立即登录/注册

微信扫码登录

0.0462s