C++多线程Singleton模式

#include <Windows.h>

//锁
class LockObject
{
	public:

		LockObject()
		{
			InitializeCriticalSection( &mLock );
		}

		virtual ~LockObject()
		{
			DeleteCriticalSection( &mLock );
		}

		void Lock()
		{
			EnterCriticalSection( &mLock );
		}

		void UnLock()
		{
			LeaveCriticalSection( &mLock );
		}

	private:

		CRITICAL_SECTION mLock;
};

template< typename T >
class Singleton
{
	protected:
		//下面默认函数全部保护起来
		Singleton()
		{}
		Singleton( const Singleton &Other );
		Singleton& operator = ( const Singleton &Other );
		virtual~Singleton()
		{}

	public:

		static T* Singleton::GetInstancePtr()
		{
			//锁
			mLock.Lock();
			if( 0 == mpInstance )
			{
				//实例化
				mpInstance = new T();
				//自动释放
				static AutoDelete Delete;
			}
			mLock.UnLock();
			return mpInstance;
		}

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

	private:

		static T* mpInstance;

		static LockObject mLock;

		//内部类防止污染环境变量仅供单件使用,并自动释放单件指针
		class AutoDelete
		{
			public:
				AutoDelete()
				{}
				~AutoDelete()
				{
					if( 0 != Singleton< T >::mpInstance )
					{
						delete Singleton< T >::mpInstance;
						Singleton< T >::mpInstance = 0;
					}
				}
		};
};

template< typename T >
T* Singleton< T >::mpInstance;
template< typename T >
LockObject Singleton< T >::mLock;

class MyClass : public Singleton< MyClass >
{
	//单件父类可以访问子类构造
	friend class Singleton< MyClass >;

	//外部不能访问
	protected:

		MyClass()
		{}

		virtual ~MyClass()
		{}
};

int main()
{
	MyClass *p = MyClass::GetInstancePtr();
	return 0;
}

你可能感兴趣的:(多线程,C++,Singleton,单件)