线程的私有数据(TSD)
2017-08-05 09:40
260 查看
我们知道 一个进程内的所有线程继承其数据与环境变量,共享数据空间,但是有时候我们需要有的线程拥有独属于其自己的数据变量,让其只在某个线程内有效,比如最常见的errno,每个线程出错的原因大不相同。 这个时候就需要创建线程的私有数据(TSD)了
线程的私有数据可以被其他函数访问,但拒绝被其他线程屏蔽
TSD采用了一键多值的技术,即一个键对应多个不同的值,每个线程访问数据时通过访问该键来得到对应的数据,在不同的线程中它对应了不同的值
其实系统为每个进程维护了一个称之为Key结构的结构数组,如下图所示:
(这里不介绍析构函数,图片来源网络)
如图,这个pthread_key_t(其实是unsigned int)类型的key,在进程中创建,一般为0~127
在上图中Key 结构的“标志”指示这个数据元素是否正在使用。在刚开始时所有的标志初始化为“不在使用”。当一个线程调用pthread_key_create创建一个新的线程特定数据元素时,系统会搜索Key结构数组,找出第一个“不在使用”的元素。并把该元素的索引(0~127)称为“键”。 返回给调用线程的正是这个索引
key一旦被创建,所有线程都可以访问它,但各线程可以根据自己的需要往key中填入不同的值,这就相当于提供了一个同名而不同值的全局变量,即一键多值
例:
运行结果为:
注:pthread_getspecific()函数返回的是与key相关联数据的指针,它是void类型的,虽然指向关联的数据地址处,但并不知道指向的数据类型,记得强转
线程的私有数据可以被其他函数访问,但拒绝被其他线程屏蔽
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类型的,虽然指向关联的数据地址处,但并不知道指向的数据类型,记得强转
相关文章推荐
- 线程的私有数据(TSD-Thread-Specific Data)
- 线程私有数据TSD
- 线程私有数据的介绍与使用(TSD)
- 线程私有数据TSD——一键多值技术,线程同步中的互斥锁和条件变量
- 【多线程编程】线程私有数据(TSD)
- SDK错误号的原理---线程私有数据(TSD)
- 线程私有数据(TSD)
- 线程私有数据TSD
- 实现一个线程安全的内存池(使用线程私有数据机制TSD来实现)
- 线程私有数据(Thread-specific Data,或TSD)
- pthread_key_create()--创建线程私有数据|pthread_key_delete()--注销线程私有数据
- 第10章 线程控制(3)_线程私有数据
- posix多线程--线程私有数据
- linux线程私有数据的保护
- 线程私有数据
- 线程私有数据(Thread-Specific Data)
- 线程控制-私有数据 转自monalisa's_blog
- 运行时数据区和线程私有/共享
- Posix线程编程指南(2)--线程私有数据
- linux线程之线程私有数据 pthread_key_create方法的学习