单例模式—饿汉模式与懒汉模式

饿汉模式
饿汉模式是线程安全

class Singleton{
  private:
    Singleton () {
    }
static Singleton* single;
  public:
static Singleton* GetTarget(){
  return single;
  }
};

懒汉模式
懒汉模式是有可能线程不安全的

下面展示不安全的写法

class Singleton2{
  private:
    Singleton2(){
    }
   static  Singleton2* single;
  public:
   static Singleton2* GetTarget(){
     if(single == NULL){
        single = new Singleton2();
     }
        return single;
   } 
};

为什么不安全?
//考虑两个线程同时首次调用GetTarget方法且同时检测到single是NULL值
//则两个线程会同时构造一个实例给single,这是严重的错误!同时,这也不是单例的唯一实现!


***懒汉模式线程安全的写法1--加锁
 

#include <iostream>
#include <unistd.h>    //加锁需要的头文件
using namespace std;

class Singleton_safe{
  private:
    Singleton_safe(){
    }
   static Singleton_safe* single;
   static pthread_mutex_t mutex;
  public:
   static Singleton_safe* GetTarget(){
     if(single == NULL){
          pthread_mutex_lock(&mutex);
          if(single == NULL){
            single = new Singleton_safe();
          }
          pthread_mutex_unlock(&mutex);
     }
    return single;
   } 
};


懒汉模式的线程安全的写法2--内部静态变量实现
 

#include <iostream>
#include <unistd.h>    //加锁需要的头文件
using namespace std;

class Singleton_safe2{
  private:
    Singleton_safe2(){
    }
    static pthread_mutex_t mutex;
  public:
    static Singleton_safe2* GetTarget(){
      pthread_mutex_lock(&mutex);
      static Singleton_safe2 obj;
      pthread_mutex_unlock(&mutex);
      return &obj;
    }
};

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值