// 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
muduo庫源碼學習(base)ThreadLocal
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.