Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4213812
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-05-15 00:14:22

    全局变量可以多个函数间共享数据,全局变量可以所有线程共有。
    但有时,需要提供线程私有的全局变量,仅在某个线程中有效。 
    线程私有数据 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)


  1. #include <stdio.h>
  2. #include <pthread.h>

  3. pthread_key_t key; //typedef int pthread_key_t

  4. void echomsg(void *t)      退出时执行
  5. { //pthread_self() 返回 unsigned long %lu
  6.     printf("destructor excuted itn thread %lu,param=%p\n",pthread_self(),((int *)t));
  7. }                                                 地址                          地址

  8. void *child1(void *a)
  9. {
  10.     int i = 10; //临时变量 栈中
  11.     unsigned long tid =pthread_self();
  12.     printf("\nset key value %d in thread %lu\n",i,tid);
  13.     
  14.     pthread_setspecific(key,&i); //key 全局变量
  15.     
  16.     printf("thread one sleep 2 until thread two finishe\n");//等待让另一个线程修改值
  17.     sleep(2);
  18.     printf("\nthread %lu retrun %d,add is %p\n",tid, *((int *)pthread_getspecific(key)), (int *)pthread_getspecific(key)); //打印当前线程中的值
  19.    地址  %p 地址
  20. }

  21. void *child2(void *b)
  22. {
  23.     int tmp = 20;
  24.     unsigned long tid = pthread_self();
  25.     printf("\nset key value %d in thread %lu\n",tmp,tid);

  26.     pthread_setspecific(key,&tmp); //key 全局变量
  27.     sleep(1);

  28.     printf("\nthread %lu retrun %d,add is %p\n",tid, *((int *)pthread_getspecific(key)), (int *)pthread_getspecific(key)); //打印当前线程中的值
  29. }

  30. int main(void)
  31. {
  32.     pthread_t tid1, tid2;

  33.     pthread_key_create(&key, echomsg);
  34.     
  35.     pthread_create(&tid1, NULL, (void *)*child1, NULL);
  36.     pthread_create(&tid2, NULL, (void *)*child2, NULL);

  37.     pthread_join(tid1, NULL);
  38.     pthread_join(tid2, NULL);
  39.     
  40.     return 0;
  41. }

  1. ywx@yuweixian:~/yu/professional/4$ ./pthread_key

  2. set key value 20 in thread 3070704496

  3. set key value 10 in thread 3079097200
  4. thread one sleep 2 until thread two finishe

  5. thread 3070704496 retrun 20,add is 0xb707338c
  6. destructor excuted itn thread 3070704496,param=0xb707338c

  7. thread 3079097200 retrun 10,add is 0xb787438c
  8. destructor excuted itn thread 3079097200,param=0xb787438c


阅读(2098) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~