C++设计模式---单例模式

适用于单线程的单例模式

Singleton.h

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

class Singleton
{
public:
    static Singleton* GetInstance();

private:
    Singleton();
    ~Singleton();
    Singleton(const Singleton&);
    Singleton& operator=(const Singleton&);
};

#endif

Singleton.cpp

#include "Singleton.h"

Singleton* Singleton::GetInstance()
{
    static Singleton s_instance;
    return &s_instance;
}

Singleton::Singleton()
{
}

Singleton::~Singleton()
{
}

C++0x以后,要求编译器保证内部静态变量的线程安全性,所以,在此种情况下,以上单例模式也是线程安全的。

线程安全的单例模式

以下利用boost库实现线程安全的单例模式。
完全参照以下这篇文章:
http://www.gocalf.com/blog/cpp-singleton.html
Singleton.h

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

class Singleton
{
public:
    static Singleton* GetInstance();

private:
    Singleton();
    ~Singleton();
    Singleton(const Singleton&);
    Singleton& operator=(const Singleton&);

    static Singleton* s_instance;
};

#endif

Singleton.cpp

#include "Singleton.h"
#include <boost\thread.hpp>

Singleton* Singleton::s_instance = 0;

Singleton* Singleton::GetInstance()
{
    static boost::mutex s_mutex;
    if (0 == s_instance)
    {
        boost::mutex::scoped_lock lock(s_mutex);
        if (0 == s_instance)
        {
            s_instance = new Singleton();
        }
    }

    return s_instance;
}

Singleton::Singleton()
{
}

Singleton::~Singleton()
{
}

线程安全的单例模式使用了double-checked locking pattern (DCLP) 机制。其实,该机制也有失效的时候,并不是百分百保险。但是一般情况下使用是足够了。
关于DCLP,具体可以参看以下两篇文章:
http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/
没想到一个貌似简简单单的线程安全单例模式竟然会有如此深奥的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值