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_THREADLOCAL_H
9#define MUDUO_BASE_THREADLOCAL_H
10
11#include <boost/noncopyable.hpp>
12#include <pthread.h>
13
14namespace muduo
15{
16
17template<typename T>
18class ThreadLocal : boost::noncopyable
19{
20 public:
21  ThreadLocal()
22  {
23    pthread_key_create(&pkey_, &ThreadLocal::destructor);
24  }
25
26  ~ThreadLocal()
27  {
28    pthread_key_delete(pkey_);
29  }
30
31  T& value()
32  {
33    T* perThreadValue = static_cast<T*>(pthread_getspecific(pkey_));
34    if (!perThreadValue) {
35      T* newObj = new T();
36      pthread_setspecific(pkey_, newObj);
37      perThreadValue = newObj;
38    }
39    return *perThreadValue;
40  }
41
42 private:
43
44  static void destructor(void *x)
45  {
46    T* obj = static_cast<T*>(x);
47    delete obj;
48  }
49
50 private:
51  pthread_key_t pkey_;
52};
53
54}
55#endif
56