但有时,需要提供线程私有的全局变量,仅在某个线程中有效。
线程私有数据 TSD thread-specific Data
typedef int pthread_key_t
该函数从TSD池中分配一项,将其地址值赋给 key 供以后访问使用,如果第二个参数不为空,在线程退出时(pthread_exit)将以 key 为所关联的数据为参数调用指向的函数,以释放分配的缓冲区
int pthread_key_create(pthread_key_t *key, viod(*deser_funciton) (void *))
注销一个TSD
int pthread_key_delete(pthread_key_t key)
读写线程私有数据
int pthread_setspecific(pthread_key_t key,const void *pointer)
void *pthread_getspecific(pthread_key_t key)
- #include <stdio.h>
-
#include <pthread.h>
-
-
pthread_key_t key; //typedef int pthread_key_t
-
-
void echomsg(void *t) 退出时执行
-
{ //pthread_self() 返回 unsigned long %lu
-
printf("destructor excuted itn thread %lu,param=%p\n",pthread_self(),((int *)t));
-
} 地址 地址
-
-
void *child1(void *a)
-
{
-
int i = 10; //临时变量 栈中
-
unsigned long tid =pthread_self();
-
printf("\nset key value %d in thread %lu\n",i,tid);
-
-
pthread_setspecific(key,&i); //key 全局变量
-
-
printf("thread one sleep 2 until thread two finishe\n");//等待让另一个线程修改值
-
sleep(2);
-
printf("\nthread %lu retrun %d,add is %p\n",tid, *((int *)pthread_getspecific(key)), (int *)pthread_getspecific(key)); //打印当前线程中的值
-
地址 %p 地址
-
}
-
-
void *child2(void *b)
-
{
-
int tmp = 20;
-
unsigned long tid = pthread_self();
-
printf("\nset key value %d in thread %lu\n",tmp,tid);
-
-
pthread_setspecific(key,&tmp); //key 全局变量
-
sleep(1);
-
-
printf("\nthread %lu retrun %d,add is %p\n",tid, *((int *)pthread_getspecific(key)), (int *)pthread_getspecific(key)); //打印当前线程中的值
-
}
-
-
int main(void)
-
{
-
pthread_t tid1, tid2;
-
-
pthread_key_create(&key, echomsg);
-
-
pthread_create(&tid1, NULL, (void *)*child1, NULL);
-
pthread_create(&tid2, NULL, (void *)*child2, NULL);
-
-
pthread_join(tid1, NULL);
-
pthread_join(tid2, NULL);
-
-
return 0;
- }
- ywx@yuweixian:~/yu/professional/4$ ./pthread_key
-
-
set key value 20 in thread 3070704496
-
-
set key value 10 in thread 3079097200
-
thread one sleep 2 until thread two finishe
-
-
thread 3070704496 retrun 20,add is 0xb707338c
-
destructor excuted itn thread 3070704496,param=0xb707338c
-
-
thread 3079097200 retrun 10,add is 0xb787438c
- destructor excuted itn thread 3079097200,param=0xb787438c