pthread 库提供了pthread_key_create, pthread_getspecific, pthread_setspecific方法操作.
原理上提供了一个 <key, pthread_t> ==> T的字典
pthread_getspecific(key) 方法的作用是<key, pthread_self()>查询这个字典, 得到对应的T*, 不同的线程, pthread_self不同, 自然会得到不同的返回值; 同一个线程中如果key不同, 也会得到不同的返回值.
理解了原理, 操作自然简单.
使用C++模板包装一下
#include <pthread.h>
template <class T>
class tls_factory
{
public:
T * create() {
return new T;
}
void destroy(T* t) {
delete t;
}
};
template <class T, class factory_cls=tls_factory<T> >
class ThreadLocal
{
private:
pthread_key_t key;
static void clear_tls(void * t) {
if(t) {
factory_cls factory;
factory.destroy((T*)t);
}
}
public:
ThreadLocal() {
pthread_key_create(&key, clear_tls);
}
T* get() {
void * data = pthread_getspecific(key);
if(data != NULL) {
return (T*)data;
} else {
factory_cls factory;
T * newT = factory.create();
pthread_setspecific(key, newT);
return newT;
}
}
void set(T * newV) {
void * data = pthread_getspecific(key);
if(data != NULL) {
clear_tls(data);
}
pthread_setspecific(newV);
}
T* operator->() {
return get();
}
T& operator*() {
return *get();
}
};
此间有个factory对象, 用来创建和销毁对象, 也可以自定义tls_factory 类作为模板参数传入, 用来定义对象的生成和销毁.
基本测试用例如
typedef struct {
int value;
} AA;
ThreadLocal<AA> locala;
ThreadLocal<AA> localb;
void * __thread_func(void * v) {
locala->value = 700;
localb->value = 800;
cout << "TA " << locala->value << endl;
cout << "TB " << localb.get()->value << endl;
}
void test_threadlocal()
{
pthread_t handle;
locala.get()->value = 100;
localb.get()->value = 200;
pthread_create(&handle, NULL, __thread_func, NULL);
pthread_join(handle, NULL);
cout << "A " << locala.get()->value << endl;
cout << "B " << localb->value << endl;
}
输出
TA 700
TB 800
A 100
B 200
分享到:
相关推荐
pthread, window pthread
用Pthread创建一个线程的简单Demo
PThread header file
pthread_testcancel pthread_kill pthread_cancel 的使用例子
pthread.lib文件下载,本人用于crf++安装时使用。。 pthread.lib文件下载,本人用于crf++安装时使用。。 pthread.lib文件下载,本人用于crf++安装时使用。。 pthread.lib文件下载,本人用于crf++安装时使用。。
简单的pthread程序 用pthread 来 计算几个数的和,了解与理解,thread,与process之间的关系。
pthread affinity pthread affinity
主要是pthread API组成的一个简单的例子,更关键的是能够熟悉pthread_join,他能够一直阻塞整个进程直到他等待的那个线程结束才能继续执行他后面的代码。 编译使用gcc pthread.c -o pthread -pthread
pthread使用手册
pthread_t newThread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&...
Pthread Primer! Pthread线程经典之作!
C++pthread线程应用
计算10,000,000内素数个数,Pthread编写线程数可调整。
里面包含pthread.h pthread.lib pthread.dll
提供c/c++多线程开发的API,兼容windows linux平台
POSIX Pthread 编程资料大全
c++封装的pthread操作,类似java的Thread
android ndk pthread
把解压库文件中的Pre-built.2文件夹中的lib,include文件复制,黏贴到c盘:Microsoft Visual Studio/VC98中去,和里面ib,include两个文件合并;再把Pre-built.2文件夹中的lib中的*dll文件复制黏贴到启动文件根目录...
linux下使用线程编程,一个对线程介绍并配有实例的文档。