转自:http://buptdtt.blog.51cto.com/2369962/975101
- //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了空间,所以用内嵌的成员对象的析构函数来释放内存。为了多线程安全,在建对象之前先加锁,完成后拆锁。
多线程需要的头文件和库文件见附件