这里实现定界加锁线程安全的单例模式

具体实现代码为:

#include<stdio.h>
#include<pthread.h>

class CLockGuard
{
public:
	CLockGuard(pthread_mutex_t* lock):m_LGLock(lock),owner(false)
	{
		GetLock(m_LGLock);
	}

	void GetLock(pthread_mutex_t* lock)
	{
		pthread_mutex_lock(lock);
		owner = true;
	}

	void ReleaseLock(pthread_mutex_t* lock)
	{
		if(owner)
		{	
			pthread_mutex_unlock(lock);
			owner = false;
		}
	}
	
	~CLockGuard()
	{
		ReleaseLock(m_LGLock);
	}
private:
	pthread_mutex_t* m_LGLock;//must be a pointer.
	bool owner;//hold by some object.
};

class Singleton
{
private:
        static pthread_mutex_t m_pLock;
        static Singleton* m_pInstance;
        Singleton(){}
public:
        static Singleton* GetInstance()
        {
                if(m_pInstance == NULL)
                {
                        CLockGuard lock(&m_pLock);
                        m_pInstance = new Singleton();
                }
                return m_pInstance;
        }
	
	static void Destory()
	{
		if(m_pInstance !=NULL)
		{
			delete m_pInstance;
			m_pInstance = NULL;
		}
	}
};

pthread_mutex_t Singleton::m_pLock = PTHREAD_MUTEX_INITIALIZER;
Singleton* Singleton::m_pInstance = NULL;

int main(int argc, char* argv[])
{
	Singleton* sig1 = Singleton::GetInstance();
	printf("sig1 = %p\n",sig1);
	Singleton* sig2 = Singleton::GetInstance();
	printf("sig2 = %p\n",sig2);
	Singleton* sig3 = Singleton::GetInstance();
	printf("sig3 = %p\n",sig3);
	Singleton::Destory();
	return 0;
}

g++ ImplementOfSingletonPattern.cpp -lpthread

你可能感兴趣的:(单例模式,线程安全,定界加锁)