您的位置:首页 > 编程语言 > C语言/C++

设计一个线程安全的单例(Singleton)模式

2015-12-08 09:43 465 查看
       在设计单例模式的时候,虽然很容易设计出符合单例模式原则的类类型,但是考虑到垃圾回收机制以及线程安全性,需要我们思考的更多。有些设计虽然可以勉强满足项目要求,但是在进行多线程设计的时候。不考虑线程安全性,必然会给我们的程序设计带来隐患。此处,我们不介绍什么是单例模式,也不介绍如何设计简单的设计模式,因为你完全可以在书上或者在博客中找到。此处我们的目的就是设计一个使用的单例模式类。单例模式需要注意与思考的问题:
(1)如何仅能实例化一个对象?
(2)怎么样设计垃圾回收机制?
(3)如何确保线程安全性?
      在思考了上述的几个问题后,首先设计一个线程安全的类,注意:由于CResGuard类会被多个线程访问,所以这个类除了构造函数与析构函数意外,其他成员都是线程安全的。
class CResGuard {
public:
CResGuard() { m_lGrdCnt = 0; InitializeCriticalSection(&m_cs); }
~CResGuard() { DeleteCriticalSection(&m_cs); }

// IsGuarded 用于调试
BOOL IsGuarded() const { return(m_lGrdCnt > 0); }

public:
class CGuard {
public:
CGuard(CResGuard& rg) : m_rg(rg) { m_rg.Guard(); };
~CGuard() { m_rg.Unguard(); }

private:
CResGuard& m_rg;
};

private:
void Guard() { EnterCriticalSection(&m_cs); m_lGrdCnt++; }
void Unguard() { m_lGrdCnt--; LeaveCriticalSection(&m_cs); }

// Guard/Unguard两个方法只能被内嵌类CGuard访问.
friend class CResGuard::CGuard;

private:
CRITICAL_SECTION m_cs;
long m_lGrdCnt;
};

       接下来我们需要设计一个符合上面三个条件的类。为了实现自动回收机制,我们使用了智能指针auto_ptr,尽管很多人不喜欢它,原因是使用不当,会产生不少陷阱,所以你完全可以用其他智能指针替代它。为了方便未来的使用,还使用了模版,如果你不喜欢,可以花两分钟的时间轻松的干掉它。
namespace Pattern
{
template <class T>
class Singleton
{
public:
static inline T* instance();

private:
Singleton(void){}
~Singleton(void){}
Singleton(const Singleton&){}
Singleton & operator= (const Singleton &){}

static auto_ptr<T> _instance;
static CResGuard _rs;
};

template <class T>
auto_ptr<T> Singleton<T>::_instance;

template <class T>
CResGuard Singleton<T>::_rs;

template <class T>
inline T* Singleton<T>::instance()
{
if (0 == _instance.get())
{
CResGuard::CGuard gd(_rs);
if (0 == _instance.get())
{
_instance.reset(new T);
}
}
return _instance.get();
}
//实现单例模式的类的地方,必须将宏定义放在声明文件中,
#define DECLARE_SINGLETON_CLASS( type ) \
friend class auto_ptr< type >; \
friend class Singleton< type >;
}
单例我们虽然看似简单,但是有太多问题非常值得我们思考与深究,因为一定程度上,它深入到了C++语言机制,更可以加深你对此语言设计的理解程度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息