1cd139dc7SShuo Chen// excerpts from http://code.google.com/p/muduo/ 2cd139dc7SShuo Chen// 3cd139dc7SShuo Chen// Use of this source code is governed by a BSD-style license 4cd139dc7SShuo Chen// that can be found in the License file. 5cd139dc7SShuo Chen// 6cd139dc7SShuo Chen// Author: Shuo Chen (giantchen at gmail dot com) 7cd139dc7SShuo Chen 8cd139dc7SShuo Chen#ifndef MUDUO_BASE_SINGLETON_H 9cd139dc7SShuo Chen#define MUDUO_BASE_SINGLETON_H 10cd139dc7SShuo Chen 11cd139dc7SShuo Chen#include <boost/noncopyable.hpp> 12cd139dc7SShuo Chen#include <pthread.h> 13cd139dc7SShuo Chen#include <stdlib.h> // atexit 14cd139dc7SShuo Chen 15cd139dc7SShuo Chennamespace muduo 16cd139dc7SShuo Chen{ 17cd139dc7SShuo Chen 18cd139dc7SShuo Chentemplate<typename T> 19cd139dc7SShuo Chenclass Singleton : boost::noncopyable 20cd139dc7SShuo Chen{ 21cd139dc7SShuo Chen public: 22cd139dc7SShuo Chen static T& instance() 23cd139dc7SShuo Chen { 24cd139dc7SShuo Chen pthread_once(&ponce_, &Singleton::init); 25cd139dc7SShuo Chen return *value_; 26cd139dc7SShuo Chen } 27cd139dc7SShuo Chen 28cd139dc7SShuo Chen private: 29cd139dc7SShuo Chen Singleton(); 30cd139dc7SShuo Chen ~Singleton(); 31cd139dc7SShuo Chen 32cd139dc7SShuo Chen static void init() 33cd139dc7SShuo Chen { 34cd139dc7SShuo Chen value_ = new T(); 35cd139dc7SShuo Chen ::atexit(destroy); 36cd139dc7SShuo Chen } 37cd139dc7SShuo Chen 38cd139dc7SShuo Chen static void destroy() 39cd139dc7SShuo Chen { 40cd139dc7SShuo Chen delete value_; 41cd139dc7SShuo Chen } 42cd139dc7SShuo Chen 43cd139dc7SShuo Chen private: 44cd139dc7SShuo Chen static pthread_once_t ponce_; 45cd139dc7SShuo Chen static T* value_; 46cd139dc7SShuo Chen}; 47cd139dc7SShuo Chen 48cd139dc7SShuo Chentemplate<typename T> 49cd139dc7SShuo Chenpthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT; 50cd139dc7SShuo Chen 51cd139dc7SShuo Chentemplate<typename T> 52cd139dc7SShuo ChenT* Singleton<T>::value_ = NULL; 53cd139dc7SShuo Chen 54cd139dc7SShuo Chen} 55cd139dc7SShuo Chen#endif 56cd139dc7SShuo Chen 57