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

个人联系方式:微信

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 <iostream>
#include <mutex>

class Singleton {
   
public:
  static Singleton* GetInstance() {
   
    if (instance_ == nullptr) {
   
      std::lock_guard<std::mutex
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值