您的位置:首页 > 其它

muduo源码分析:线程特定/私有数据类ThreadLocal

2015-12-13 16:19 363 查看


线程私有数据

1.__thread : gcc内置的线程局部存储设施

__thread只能修饰POD类型

POD类型(plain old data),与C兼容的原始数据,例如,结构和整型等C语言中的类型是 POD 类型,但带有用户定义的构造函数或虚函数的类则不是

__thread string t_obj1(“cppcourse”); // 错误,不能调用对象的构造函数

__thread string* t_obj2 = new string; // 错误,初始化只能是编译期常量

__thread string* t_obj3 = NULL; // 正确


2.Posix线程私有数据

(Thread-specific Date)TSD

实现原理: /article/9373162.html/article/2934789.html

相当于二级索引,key数组(一级索引)整个进程共享,标志哪些key使用与否,每个线程有自己pkey数组(二级索引),存在pthread结构中,pkey数组存储自己私有数据的指针。key --》pkey- -》私有数据指针

pthread_key_create(创建一个键),pthread_setspecific(为一个键设置线程私有数据),pthread_getspecific(从一个键读取线程私有数据),pthread_key_delete(删除一个键)。这几个函数的声明如下:

#include <pthread.h>

int pthread_key_create(pthread_key_t *key,void (*destr_function)(void *));

int pthread_setspecific(pthread_key_t key,const void *pointer));

void *pthread_getspecific(pthread_key_t key);

int pthread_key_delete(pthread_key_t key);

单例+特定数据
// Singleton 所管理的对象是 ThreadLocal<Test> ,ThreadLocal<Test> 在进程内是单例,所有线程共一个ThreadLocal<Test>
实例
Singleton调用instance方法获取ThreadLocal<Test>对象,ThreadLocal<Test>对象调用ThreadLocal<Test>::value方法获取Test类型线程特定数据的引用,value返回的是各自线程特定数据引用。Singleton确保进程范围内ThreadLocal<Test>实例只有一个,所有线程共这一个;ThreadLocal确保Test有多个,即在每个线程都有

#define STL muduo::Singleton<muduo::ThreadLocal<Test> >::instance().value()

#ifndef MUDUO_BASE_THREADLOCAL_H
#define MUDUO_BASE_THREADLOCAL_H

#include <boost/noncopyable.hpp>
#include <pthread.h>
namespace muduo
{

template<typename T>
class ThreadLocal : boost::noncopyable
{
public:
ThreadLocal()
{
pthread_key_create(&key_, &ThreadLocal::destroy);
}
~ThreadLocal()
{
pthread_key_delete(key_);
}

T& value()
{
T* ret = static_cast<T*>(pthread_getspecific(key_));
if(!ret)
{
ret = new T();
pthread_setspecific(key_, ret);
}
return *ret;
}
private:
//静态!!!!!!
static void destroy(void *x)
{
T* obj = static_cast<T*>(x);
typedef char T_must_be_complete_type[sizeof(T)==0?-1:1];
T_must_be_complete_type tt;
delete obj;
}
private:
pthread_key_t key_;
};

}

#endif


参考:c++教程网

muduo网络库

linux多线程服务器端编程》.陈硕
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: