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_SINGLETON_H
9#define MUDUO_BASE_SINGLETON_H
10
11#include <boost/noncopyable.hpp>
12#include <pthread.h>
13#include <stdlib.h> // atexit
14
15namespace muduo
16{
17
18template<typename T>
19class Singleton : boost::noncopyable
20{
21 public:
22  static T& instance()
23  {
24    pthread_once(&ponce_, &Singleton::init);
25    return *value_;
26  }
27
28 private:
29  Singleton();
30  ~Singleton();
31
32  static void init()
33  {
34    value_ = new T();
35    ::atexit(destroy);
36  }
37
38  static void destroy()
39  {
40    delete value_;
41  }
42
43 private:
44  static pthread_once_t ponce_;
45  static T*             value_;
46};
47
48template<typename T>
49pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT;
50
51template<typename T>
52T* Singleton<T>::value_ = NULL;
53
54}
55#endif
56
57