- //Singleton.h
- #ifndef _SINGLETON_H_
- #define _SINGLETON_H_
- #include <iostream>
- #include <pthread.h>
- using namespace std;
- class locker
- {
- public:
- inline locker(){ pthread_mutex_init(&mutex,NULL);}
- inline ~locker(){ pthread_mutex_destroy(&mutex);}
- inline void lock(){ pthread_mutex_lock(&mutex);}
- inline void unlock(){ pthread_mutex_unlock(&mutex);}
- private:
- pthread_mutex_t mutex;
- };
- class Singleton
- {
- public:
- static Singleton* Instance();
- private:
- Singleton();
- static Singleton * m_pInstance;
- class Garbo//刪除Singleton實例的對象
- {
- public:
- ~Garbo()
- {
- if(Singleton::m_pInstance)
- {
- delete Singleton::m_pInstance;
- }
- }
- };
- static Garbo gb;//在程序結束時,系統會調用它的析構函數
- };
- #endif //~_SINGLETON_H_
- //Singleton.cpp
- #include "Singleton.h"
- #include <iostream>
- using namespace std;
- Singleton* Singleton::m_pInstance = 0;
- Singleton::Singleton()
- {
- cout<<"Singleton...."<<endl;
- }
- Singleton* Singleton::Instance()
- {
- if(NULL == m_pInstance)
- {
- locker llock;
- llock.lock();
- if(NULL == m_pInstance)
- {
- m_pInstance = new Singleton();
- }
- llock.unlock();
- }
- return m_pInstance;
- }
- //main.cpp
- #include "Singleton.h"
- #include <iostream>
- using namespace std;
- int main(int argc,char* argv[])
- {
- Singleton* sgn = Singleton::Instance();
- return 0;
- }
將構造函數聲明爲private,防止被實例化。用一個靜態成員變量和靜態函數實現惟一的對象構造。在靜態函數中new了空間,因此用內嵌的成員對象的析構函數來釋放內存。爲了多線程安全,在建對象以前先加鎖,完成後拆鎖。ios
多線程須要的頭文件和庫文件見附件安全