设计模式
单例模式 http://blog.csdn.net/hackbuteer1/article/details/7460019
#include<stdio.h> #include<pthread.h> #include<memory> class Lock{ private: pthread_mutex_t _mutex; public: Lock(){ pthread_mutex_init(&_mutex, NULL); } ~Lock(){ pthread_mutex_destroy(&_mutex); } void lock(){ pthread_mutex_lock(&_mutex); } void unlock(){ pthread_mutex_unlock(&_mutex); } }; class Guard{ public: explicit Guard(Lock* lock){ _lock = lock; if(_lock){ _lock->lock(); } } ~Guard(){ if(_lock){ _lock->unlock(); } } private: Lock* _lock; }; class Singleton{ private: Singleton(){} virtual ~Singleton(){} Singleton(const Singleton &){} Singleton& operator=(const Singleton&){} static Singleton * _instance; static Lock _lock; public: static Singleton* get_instance(){ if (_instance == NULL){ Guard guard(&_lock); if(_instance == NULL){ _instance = new(std::nothrow) Singleton(); if(_instance == NULL){ perror("new instance FATAL"); return NULL; } } } return _instance; } void do_sth(){ printf("this is a singleton\n"); } }; Singleton * Singleton::_instance = NULL; Lock Singleton::_lock; int main(int argc, char* argv[]){ Singleton* sing = Singleton::get_instance(); sing->do_sth(); return 0; }