__thread关键字前面已经学过了。其实本质上,线程特定数据的数据结构如下:
注意,实际数据在堆空间上。
ThreadLocal< T >类
核心点:每创建一个ThreadLocal对象,就能创建一个线程特定数据,数据类型为T
ThreadLocal.h
#ifndef MUDUO_BASE_THREADLOCAL_H
#define MUDUO_BASE_THREADLOCAL_H
#include <boost/noncopyable.hpp>
#include <pthread.h>
namespace muduo
{
//核心点:每创建一个ThreadLocal对象,就能创建一个线程特定数据,数据类型为T
template<typename T>
class ThreadLocal : boost::noncopyable
{
public:
ThreadLocal()
{
pthread_key_create(&pkey_, &ThreadLocal::destructor);//绑定回调函数
}
~ThreadLocal()
{
pthread_key_delete(pkey_);//同时会自动调用回调函数
}
T& value()//重点
{
T* perThreadValue = static_cast<T*>(pthread_getspecific(pkey_));
if (!perThreadValue) {//如果pkey_没有绑定value
T* newObj = new T();//重点,创建一个线程特定数据,数据类型为T
pthread_setspecific(pkey_, newObj);//类似key-value绑定
perThreadValue = newObj;
}
return *perThreadValue;
}
private:
static void destructor(void *x)
{
T* obj = static_cast<T*>(x);
typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1];
delete obj;
}
private:
pthread_key_t pkey_;
};
}
#endif
测试
自己写了个测试程序:
#include <muduo/base/ThreadLocal.h>
#include <muduo/base/CurrentThread.h>
#include <muduo/base/Thread.h>
#include <muduo/base/Singleton.h>
#include <boost/noncopyable.hpp>
#include <stdio.h>
class Test : boost::noncopyable
{
public:
Test()
{
printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this);
}
~Test()
{
printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, name_.c_str());
}
const std::string& name() const { return name_; }
void setName(const std::string& n) { name_ = n; }
private:
std::string name_;
};
class Test1 : boost::noncopyable
{
public:
Test1()
{
printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this);
}
~Test1()
{
printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, name_.c_str());
}
const std::string& name() const { return name_; }
void setName(const std::string& n) { name_ = n; }
private:
std::string name_;
};
muduo::ThreadLocal<Test> testObj1;
//创建一个线程特定数据,数据类型是Test,各个线程通过testObj1.value()获取自己的特定数据,每个线程都有一份,相互独立
muduo::ThreadLocal<Test> testObj2;
//再创建一个线程特定数据,数据类型也是Test,各个线程通过testObj2.value()获取自己的特定数据,每个线程都有一份,相互独立
#define STL muduo::Singleton<muduo::ThreadLocal<Test1> >::instance().value()
//muduo::ThreadLocal<Test1>是单例的,说明只能创建一个数据类型为Test1的线程特定数据,各个线程通过STL获取自己的特定数据,每个线程都有一份,相互独立
void print()
{
printf("tid=%d, obj1 %p name=%s\n",
muduo::CurrentThread::tid(),
&testObj1.value(),
testObj1.value().name().c_str());
printf("tid=%d, obj2 %p name=%s\n",
muduo::CurrentThread::tid(),
&testObj2.value(),
testObj2.value().name().c_str());
printf("tid=%d, muduo::Singleton<muduo::ThreadLocal<Test1> >::instance() %p name=%s\n",
muduo::CurrentThread::tid(),
&STL,
STL.name().c_str());
}
void threadFunc()
{
print();
}
int main()
{
testObj1.value().setName("main one");
testObj2.value().setName("main two");
STL.setName("main three");
print();
muduo::Thread t1(threadFunc);
t1.start();
t1.join();
pthread_exit(0);
}
这个例子还是证明了线程特定数据是线程私有的全局变量,每个线程都有一份,相互独立。