muduo库源码学习(base)ThreadLocal

// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)

#ifndef MUDUO_BASE_THREADLOCAL_H
#define MUDUO_BASE_THREADLOCAL_H

#include   // MCHECK
#include 

#include 

namespace muduo
{

template
class ThreadLocal : noncopyable
{
 public:
  ThreadLocal()
  {
    MCHECK(pthread_key_create(&pkey_, &ThreadLocal::destructor));//系统调用这个回调函数
  }

  ~ThreadLocal()
  {
    MCHECK(pthread_key_delete(pkey_));//只是从线程里删除key
  }

  T& value()
  {
    T* perThreadValue = static_cast(pthread_getspecific(pkey_));
    if (!perThreadValue)
    {
      T* newObj = new T();
      MCHECK(pthread_setspecific(pkey_, newObj));
      perThreadValue = newObj;
    }
    return *perThreadValue;
  }

 private:

  static void destructor(void *x)//静态函数。线程结束时,系统调用它(不是public函数!)删除
  {
    T* obj = static_cast(x);//如果没有调用value()呢?
    typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1];//T_must_be_complete_type现在是个类型,char[10]
    T_must_be_complete_type dummy; (void) dummy;
    delete obj;
  }

 private:
  pthread_key_t pkey_;//线程局部对象依靠这个key得到对象
};

}
#endif

你可能感兴趣的:(C++,muduo)