1// excerpts from http://code.google.com/p/muduo/ 2// 3// Use of this source code is governed by a BSD-style license 4// that can be found in the License file. 5// 6// Author: Shuo Chen (giantchen at gmail dot com) 7 8#ifndef MUDUO_BASE_THREADLOCALSINGLETON_H 9#define MUDUO_BASE_THREADLOCALSINGLETON_H 10 11#include <boost/noncopyable.hpp> 12 13namespace muduo 14{ 15 16template<typename T> 17class ThreadLocalSingleton : boost::noncopyable 18{ 19 public: 20 21 static T& instance() 22 { 23 if (!t_value_) 24 { 25 t_value_ = new T(); 26 } 27 return *t_value_; 28 } 29 30 // See muduo/base/ThreadLocalSingleton.h for how to delete it automatically. 31 static void destroy() 32 { 33 delete t_value_; 34 t_value_ = 0; 35 } 36 37 private: 38 ThreadLocalSingleton(); 39 ~ThreadLocalSingleton(); 40 41 static __thread T* t_value_; 42}; 43 44template<typename T> 45__thread T* ThreadLocalSingleton<T>::t_value_ = 0; 46 47} 48#endif 49