多线程单例模式
发布日期:2022-04-11 08:52:59 浏览次数:19 分类:博客文章

本文共 5171 字,大约阅读时间需要 17 分钟。

多线程单例模式

原文:https://blog.csdn.net/u011726005/article/details/82356538 

 

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
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
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写的一篇文章里面专门分析了这种解决方案的问题。文章截图:

 

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

if (instance_ == nullptr) {  \\ 语句1      std::lock_guard
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是一种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中静态变量的初始化时线程安全的。通过调试,在进行局部静态变量初始化的时候,确实会执行以下代码来保证线程安全。

 

================= End

 

转载地址:https://www.cnblogs.com/lsgxeva/p/11170659.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:多线程卖票
下一篇:多线程单例安全----双重校验锁+volatile

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月20日 12时40分20秒