muduo库源码学习(base)ThreadLocal

来源:互联网 发布:plc与单片机的3000介绍 编辑:程序博客网 时间:2024/06/05 20:08
// 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 <muduo/base/Mutex.h>  // MCHECK#include <muduo/base/noncopyable.h>#include <pthread.h>namespace muduo{template<typename T>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<T*>(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<T*>(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

原创粉丝点击