- 单线程中,用“全局变量”以实现多个函数间共享数据。
- 多线程环境下,由于数据空间是共享的,因此全局变量也为所有线程所共有。
- 但有时需要 线程私有的全局变量,仅在某个线程中有效,但却可以跨多个函数访问。
- POSIX线程库 通过维护一定的数据结构来解决这个问题,这些数据称为Thread-specific Data.
也称线程本地存储Thread-Local-Storage - 对于POD类型的线程本地存储,可以用
__thread
关键字。
#include <boost/noncopyable.hpp>
#include <pthread.h>
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)
{
T* newObj = new T();
pthread_setspecific(pkey_, newObj);
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];
T_must_be_complete_type dummy; (void) dummy;
delete obj;
}
private:
pthread_key_t pkey_;
};
Posix定义了4个API
(1) 创建TSD
#include <pthread.h>
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
该函数从TSD池中分配一项,将其值赋给key供以后访问使用。如果destr_function不为空,在线程退出(pthread_exit())时将以key所关联的数据为参数调用destr_function(),以释放分配的缓冲区。不论哪个线程调用pthread_key_create(),所创建的key都是所有线程可访问的,但各个线程可根据自己的需要往key中填入不同的值,这就相当于提供了一个同名而不同值的全局变量。在LinuxThreads的实现中,TSD池用一个结构数组表示:
(2) 注销一个TSD
#include <pthread.h>
int pthread_key_delete(pthread_key_t key);
这个函数并不检查当前是否有线程正使用该TSD,也不会调用清理函数(destr_function),而只是将TSD释放以供下一次调用pthread_key_create()使用。在LinuxThreads中,它还会将与之相关的线程数据项设为NULL。
(3) TSD的读写API
#include <pthread.h>
int pthread_setspecific(pthread_key_t key, const void *pointer)
void * pthread_getspecific(pthread_key_t key)
写入(pthread_setspecific())时,将pointer的值(不是所指的内容)与key相关联,而相应的读出函数则将与key相关联的数据读出来。数据类型都设为void *,因此可以指向任何类型的数据。