线程安全的Singleton实现

template<typename T>
class Singleton : boost::noncopyable {
public:
    static T& getInstance(){
        pthread_once(&ponce_, Singleton::init);
        return *instance_;
    } 
private:
    static void init() {
         instance_ = new T();
    }
private:
    static pthread_once_t ponce_;
    static T* instance_;
};

template<typename T> 
pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT;

template<typename T>
T* Singleton<T>::instance_ = NULL;

shiyang6017
158 声望59 粉丝