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_THREADLOCALSINGLETON_H 9cd139dc7SShuo Chen#define MUDUO_BASE_THREADLOCALSINGLETON_H 10cd139dc7SShuo Chen 11cd139dc7SShuo Chen#include <boost/noncopyable.hpp> 12cd139dc7SShuo Chen 13cd139dc7SShuo Chennamespace muduo 14cd139dc7SShuo Chen{ 15cd139dc7SShuo Chen 16cd139dc7SShuo Chentemplate<typename T> 17cd139dc7SShuo Chenclass ThreadLocalSingleton : boost::noncopyable 18cd139dc7SShuo Chen{ 19cd139dc7SShuo Chen public: 20cd139dc7SShuo Chen 21cd139dc7SShuo Chen static T& instance() 22cd139dc7SShuo Chen { 23cd139dc7SShuo Chen if (!t_value_) 24cd139dc7SShuo Chen { 25cd139dc7SShuo Chen t_value_ = new T(); 26cd139dc7SShuo Chen } 27cd139dc7SShuo Chen return *t_value_; 28cd139dc7SShuo Chen } 29cd139dc7SShuo Chen 30ac2f0106SShuo Chen // See muduo/base/ThreadLocalSingleton.h for how to delete it automatically. 31cd139dc7SShuo Chen static void destroy() 32cd139dc7SShuo Chen { 33cd139dc7SShuo Chen delete t_value_; 34cd139dc7SShuo Chen t_value_ = 0; 35cd139dc7SShuo Chen } 36cd139dc7SShuo Chen 37cd139dc7SShuo Chen private: 38ac2f0106SShuo Chen ThreadLocalSingleton(); 39ac2f0106SShuo Chen ~ThreadLocalSingleton(); 40cd139dc7SShuo Chen 41cd139dc7SShuo Chen static __thread T* t_value_; 42cd139dc7SShuo Chen}; 43cd139dc7SShuo Chen 44cd139dc7SShuo Chentemplate<typename T> 45cd139dc7SShuo Chen__thread T* ThreadLocalSingleton<T>::t_value_ = 0; 46cd139dc7SShuo Chen 47cd139dc7SShuo Chen} 48cd139dc7SShuo Chen#endif 49