线程安全的单例模式

一、懒汉模式:即第一次调用该类实例的时候产生一个新的该类实例,并在以后仅返回此实例。

需要用锁,来保证其线程安全性:原因:多个线程可能进入判断是否已经存在实例的if语句,从而non thread safety.

使用double-check来保证thread safety.但是如果处理大量数据时,该锁才成为严重的性能瓶颈。

1、静态成员实例的懒汉模式:

class Singleton
{
private:
    static Singleton* m_instance;
    Singleton(){}
public:
     static Singleton* getInstance();
};

Singleton* Singleton::getInstance()
{
     if(NULL == m_instance)
     {
     Lock();//借用其它类来实现,如boost
     if(NULL == m_instance)
     {
         m_instance = new Singleton;
     }
     UnLock();
     }
     return m_instance;
}

2、内部静态实例的懒汉模式

这里需要注意的是,C++0X以后,要求编译器保证内部静态变量的线程安全性,可以不加锁。但C++ 0X以前,仍需要加锁。

class SingletonInside
{
private:
     SingletonInside(){}
public:
     static SingletonInside* getInstance()
     {
     Lock(); // not needed after C++0x
     static SingletonInside instance;
     UnLock(); // not needed after C++0x
     return instance; 
     }
};

二、饿汉模式:即无论是否调用该类的实例,在程序开始时就会产生一个该类的实例,并在以后仅返回此实例。

由静态初始化实例保证其线程安全性,WHY?因为静态实例初始化在程序开始时进入主函数之前就由主线程以单线程方式完成了初始化,不必担心多线程问题。

故在性能需求较高时,应使用这种模式,避免频繁的锁争夺。

class SingletonStatic
{
private:
     static const SingletonStatic* m_instance;
     SingletonStatic(){}
public:
     static const SingletonStatic* getInstance()
     {
     return m_instance;
     }
};
//外部初始化 before invoke main
const SingletonStatic* SingletonStatic::m_instance = new SingletonStatic;

1.懒汉式是以时间换空间的方式。

2.饿汉式是以空间换时间的方式。

http://www.liyuduo.com/?p=2898

实现按需创建实例

class Singleton
{
private:
     static const Singleton* m_instance;
     SingletonStatic(){}
public:
     static Singleton* getInstance()
     {
         return Nested.m_instance;
     }
    class Nested
    {
        static Nested() {}
        static Singleton *m_instance = new Singleton();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值