我们知道 一个进程内的所有线程继承其数据与环境变量,共享数据空间,但是有时候我们需要有的线程拥有独属于其自己的数据变量,让其只在某个线程内有效,比如最常见的errno,每个线程出错的原因大不相同。 这个时候就需要创建线程的私有数据(TSD)了
线程的私有数据可以被其他函数访问,但拒绝被其他线程屏蔽 TSD采用了一键多值的技术,即一个键对应多个不同的值,每个线程访问数据时通过访问该键来得到对应的数据,在不同的线程中它对应了不同的值
其实系统为每个进程维护了一个称之为Key结构的结构数组,如下图所示: (这里不介绍析构函数,图片来源网络) 如图,这个pthread_key_t(其实是unsigned int)类型的key,在进程中创建,一般为0~127
在上图中Key 结构的“标志”指示这个数据元素是否正在使用。在刚开始时所有的标志初始化为“不在使用”。当一个线程调用pthread_key_create创建一个新的线程特定数据元素时,系统会搜索Key结构数组,找出第一个“不在使用”的元素。并把该元素的索引(0~127)称为“键”。 返回给调用线程的正是这个索引
key一旦被创建,所有线程都可以访问它,但各线程可以根据自己的需要往key中填入不同的值,这就相当于提供了一个同名而不同值的全局变量,即一键多值
例:
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<pthread.h> #include<unistd.h> pthread_key_t key; void *thread2( void *arg ) { int tsd = 5; printf( "thread2 %lu is running \n",pthread_self() ); pthread_setspecific( key,&tsd ); printf( "thread2 %lu returns %d\n",pthread_self(),*(int *)pthread_getspecific(key) ); } void *thread1( void *arg ) { int tsd = 0; pthread_t thid2; printf( "thread1 %lu is running\n",pthread_self() ); pthread_setspecific( key,&tsd ); pthread_create( &thid2,NULL,thread2,NULL ); sleep( 3 ); printf( "thread1 %lu returns %d\n",pthread_self(),*(int *)pthread_getspecific(key) ); } int main() { pthread_t thid1; int statl; printf( "main thread begins running\n" ); pthread_key_create( &key,NULL ); pthread_create( &thid1,NULL,thread1,NULL ); sleep(5); pthread_key_delete(key); printf( "main thread exit\n" ); return 0; }运行结果为:
注:pthread_getspecific()函数返回的是与key相关联数据的指针,它是void类型的,虽然指向关联的数据地址处,但并不知道指向的数据类型,记得强转