实现了一个多线程安全的单例模式:
以下的单例模式,如果想要成为一个基础的基类,可以将private设为protect,将instance类型写成模版形式,那么想要实现新的单例,直接继承此单例模式就好了。
Singleton* Singleton::instance = NULL;pthread_mutex_t Singleton::mutex = PTHREAD_MUTEX_INITIALIZER;Singleton* Singleton::GetInstance() { if(NULL == instance) { pthread_mutex_lock(&mutex); instance = new Singleton(); pthread_mutex_unlock(&mutex); } return instance;}class Singleton { public: static Singleton* GetInstance(); void PrintTest() { printf("hello world\n"); } private: Singleton(){}; private: class CGarbo { public: ~CGarbo() { if(NULL != Singleton::instance) delete Singleton::instance; pthread_mutex_destroy(&mutex); } }; static CGarbo Garbo; static Singleton* instance ; static pthread_mutex_t mutex;};