c++ 单例模式_C++ 线程安全的单例模式

(给CPP开发者加星标,提升C/C++技能)

来源: 哲这这 https://blog.csdn.net/u011726005/article/details/82356538

【导读】:单例模式(Singleton Pattern)是最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。那么在多线程的情况下,怎么确保单例模式的安全性呢?请跟着小编一起来学习吧。

以下是正文


1. 饿汉模式

使用饿汉模式实现单例是十分简单的,并且有效避免了线程安全问题,因为将该单例对象定义为static变量,程序启动即将其构造完成了。代码实现:

class Singleton {public:  static Singleton* GetInstance() {    return singleton_;  }  static void DestreyInstance() {    if (singleton_ != NULL) {      delete singleton_;    }  }private:  // 防止外部构造。  Singleton() = default;  // 防止拷贝和赋值。  Singleton& operator=(const Singleton&) = delete;  Singleton(const Singleton& singleton2) = delete;private:  static Singleton* singleton_;};Singleton* Singleton::singleton_ = new Singleton;int main() {  Singleton* s1 = Singleton::GetInstance();  std::cout << s1 << std::endl;  Singleton* s2 = Singleton::GetInstance();  std::cout << s2 << std::endl;  Singleton.DestreyInstance();  return 0;}

2.懒汉模式

饿汉方式不论是否需要使用该对象都将其定义出来,可能浪费了内存,或者减慢了程序的启动速度。所以使用懒汉模式进行优化,懒汉模式即延迟构造对象,在第一次使用该对象的时候才进行new该对象。
而懒汉模式会存在线程安全问题,最出名的解决方案就是Double-Checked Locking Pattern (DCLP)。使用两次判断来解决线程安全问题并且提高效率。代码实现:

#include #include class Singleton {public:  static Singleton* GetInstance() {    if (instance_ == nullptr) {      std::lock_guard<std::mutex> lock(mutex_);      if (instance_ == nullptr) {        instance_ = new Singleton;      }    }    return instance_;  }  ~Singleton() = default;  // 释放资源。  void Destroy() {    if (instance_ != nullptr) {      delete instance_;      instance_ = nullptr;    }  }  void PrintAddress() const {    std::cout << this << std::endl;  }private:  Singleton() = default;  Singleton(const Singleton&) = delete;  Singleton& operator=(const Singleton&) = delete;private:  static Singleton* instance_;  static std::mutex mutex_;};Singleton* Singleton::instance_ = nullptr;std::mutex Singleton::mutex_;int main() {  Singleton* s1 = Singleton::GetInstance();  s1->PrintAddress();  Singleton* s2 = Singleton::GetInstance();  s2->PrintAddress();  return 0;}

3. 懒汉模式优化

上述代码有一个问题,当程序使用完该单例,需要手动去调用Destroy()来释放该单例管理的资源。如果不去手动释放管理的资源(例如加载的文件句柄等),虽然程序结束会释放这个单例对象的内存,但是并没有调用其析构函数去关闭这些管理的资源句柄等。解决办法就是将该管理的对象用智能指针管理。代码如下:

#include #include #include class Singleton {public:  static Singleton& GetInstance() {    if (!instance_) {      std::lock_guard<std::mutex> lock(mutex_);      if (!instance_) {        instance_.reset(new Singleton);      }    }    return *instance_;  }  ~Singleton() = default;  void PrintAddress() const {    std::cout << this << std::endl;  }private:  Singleton() = default;  Singleton(const Singleton&) = delete;  Singleton& operator=(const Singleton&) = delete;private:  static std::unique_ptr instance_;  static std::mutex mutex_;};std::unique_ptr Singleton::instance_;std::mutex Singleton::mutex_;int main() {  Singleton& s1 = Singleton::GetInstance();  s1.PrintAddress();  Singleton& s2 = Singleton::GetInstance();  s2.PrintAddress();  return 0;}

4. Double-Checked Locking Pattern存在的问题

Double-Checked Locking Pattern (DCLP)实际上也是存在严重的线程安全问题。Scott Meyers and 和Alexandrescu写的一篇文章里面专门分析了这种解决方案的问题C++ and the Perils of Double-Checked Locking。文章截图:a247a771406d8a736c33f597f3ee64b0.png3c8440c1445825d27bd3d6571d8d7b05.pngfca8bbe12883c8ede97608d70ac00bfd.png

比如刚刚实现方式很容易发现其存在线程安全问题。

if (instance_ == nullptr) {  \\ 语句1  std::lock_guard<std::mutex> lock(mutex_);  if (instance_ == nullptr) {    instance_ = new Singleton;  \\ 语句2  }}

线程安全问题产生的原因是多个线程同时读或写同一个变量时,会产生问题。


如上代码,对于语句2是一个写操作,我们用mutex来保护instance_这个变量。但是语句1是一个读操作,if (instance_ == nullptr),这个语句是用来读取instance_这个变量,而这个读操作是没有锁的。所以在多线程情况下,这种写法明显存在线程安全问题。


《C++ and the Perils of Double-Checked Locking》这篇文章中提到:

instance_ = new Singleton;

这条语句实际上做了三件事,第一件事申请一块内存,第二件事调用构造函数,第三件是将该内存地址赋给instance_。

但是不同的编译器表现是不一样的。可能先将该内存地址赋给instance_,然后再调用构造函数。这是线程A恰好申请完成内存,并且将内存地址赋给instance_,但是还没调用构造函数的时候。线程B执行到语句1,判断instance_此时不为空,则返回该变量,然后调用该对象的函数,但是该对象还没有进行构造。

5. 使用std::call_once实现单例

在C++11中提供一种方法,使得函数可以线程安全的只调用一次。即使用std::call_once和std::once_flag。std::call_once是一种lazy load的很简单易用的机制。实现代码如下:

#include #include #include class Singleton {public:  static Singleton& GetInstance() {    static std::once_flag s_flag;    std::call_once(s_flag, [&]() {      instance_.reset(new Singleton);    });    return *instance_;  }  ~Singleton() = default;  void PrintAddress() const {    std::cout << this << std::endl;  }private:  Singleton() = default;  Singleton(const Singleton&) = delete;  Singleton& operator=(const Singleton&) = delete;private:  static std::unique_ptr instance_;};std::unique_ptr Singleton::instance_;int main() {  Singleton& s1 = Singleton::GetInstance();  s1.PrintAddress();  Singleton& s2 = Singleton::GetInstance();  s2.PrintAddress();  return 0;}

6.使用局部静态变量实现懒汉

使用C++局部静态变量也可解决上述问题。

#include class Singleton {public:  static Singleton& GetInstance() {    static Singleton intance;    return intance;  }  ~Singleton() = default;private:  Singleton() = default;  Singleton(const Singleton&) = delete;  Singleton& operator=(const Singleton&) = delete;};int main() {  Singleton& s1 = Singleton::GetInstance();  std::cout << &s1 << std::endl;  Singleton& s2 = Singleton::GetInstance();  std::cout << &s2 << std::endl;  return 0;}

局部静态变量可以延迟对象的构造,等到第一次调用时才进行构造。

C++11中静态变量的初始化时线程安全的。通过调试,在进行局部静态变量初始化的时候,确实会执行以下代码来保证线程安全。a6552379fea37d1486c7f551fe6398b3.png

- EOF -

推荐阅读   点击标题可跳转

1、1.5 万 Star!界面酷炫、简单易用的数据库开源客户端

2、C++ 随机数初探

3、看完这篇你还能不懂 C 语言 /C++ 内存管理?

关于 C++ 线程安全的单例模式,欢迎在评论中和我探讨。觉得文章不错,请点赞和在看支持我继续分享好文。谢谢!

关注『CPP开发者』

看精选C++技术文章 . 加C++开发者专属圈子

↓↓↓

5605308239507dc9b0c6b20fa1fa1ddf.png

点赞和在看就是最大的支持❤️

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值