C++11实现线程安全的单例模式(使用std call_once)_c++ 单例 std call_once

Singleton.DestreyInstance();

return 0;
}


#### 2.懒汉模式


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



#include
#include

class Singleton {
public:
static Singleton* GetInstance() {
if (instance_ == nullptr) {
std::lock_guardstd::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_guardstd::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]( )。文章截图:  
 ![这里写图片描述](https://img-blog.csdn.net/2018090322494171?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTE3MjYwMDU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)  
 ![这里写图片描述](https://img-blog.csdn.net/20180903224953460?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTE3MjYwMDU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)  
 ![这里写图片描述](https://img-blog.csdn.net/20180903225002252?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTE3MjYwMDU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)


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



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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值