跋涉之旅之Posix线程编程指南(2)

原文链接

 

概念及作用

在单线程程序中,我们经常要用到"全局变量"以实现多个函数间共享数据。在多线程环境下,由于数据空间是共享的,因此全局变量也为所有线程所共有。但有时 应用程序设计中有必要提供线程私有的全局变量,仅在某个线程中有效,但却可以跨多个函数访问 ,比如程序可能需要每个线程维护一个链表,而使用相同的函数操 作,最简单的办法就是使用同名而不同变量地址的线程相关数据结构 。这样的数据结构可以由Posix线程库维护,称为线程私有数据 (Thread- specific Data,或TSD)。

 

创建和注销

Posix定义了两个API分别用来创建和注销TSD:

 

该函数从TSD池中分配一项,将其值赋给key供以后访问使用 。如果destr_function不为空,在线程退出(pthread_exit())时将以key所关联的数据为参数调用destr_function(),以释放分配的缓冲区 (用于收尾工作)。

 

  1. int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *));  

 

不论哪个线程调用pthread_key_create(),所创建的key都是所有线程可访问 的,但各个线程可根据自己的需要往key中填入不同的值 ,这就相当于提供了一个同名而不同值的全局变量。在LinuxThreads的实现中,TSD池用一个结构数组 表示:

  1. static struct pthread_key_struct pthread_keys[PTHREAD_KEYS_MAX] = { { 0, NULL } };  

 

创建一个TSD就相当于 将结构数组中的某一项设置为"in_use" ,并将其索引返回给*key,然后设置destructor函数为destr_function。

注销一个TSD采用如下API:

  1. int pthread_key_delete(pthread_key_t key);  

 

这个函数并不检查当前是否有线程正使用该TSD,也不会调用清理函数(destr_function) ,而只是将TSD释放以供下一次调用 pthread_key_create()使用 。在LinuxThreads中,它还会将与之相关的线程数据项设为NULL (见"访问")(单纯的设置为NULL是否会造成内存泄露的问题 ?)。

 

访问

TSD的读写都通过专门的Posix Thread函数进行,其API定义如下:

  1. int  pthread_setspecific(pthread_key_t  key,  const   void  *pointer);  
  2. void * pthread_getspecific(pthread_key_t key);  

 

写入(pthread_setspecific())时,将pointer的值(不是所指的内容 )(这样的操作是否会出现问题?作为函数参数传入的指针只是原来指针的副本吧?写程序测试! 测试结果表明,我错了……)与key相关联 (底层实现是类似于红黑树的结构体么? ),而相应的读出函数则将与key相关联的数据读出来。数据类型都设为void *,因此可以指向任何类型的数据 。

测试代码:

  1. #include <iostream>  
  2. #include <cstdio>  
  3. using namespace std;  
  4. void CheckPointerValue(const void *pVoid)  
  5. {  
  6.     printf("the pointer's value is :%p/n",pVoid);  
  7. }  
  8. int main()  
  9. {  
  10.     int i = 100;  
  11.     int *pInt = &i;  
  12.     printf("original pointer's value = %p/n",pInt);  
  13.     CheckPointerValue(pInt);  
  14.     return 0;  
  15. }  

输出结果是相等的。

 

在LinuxThreads中,使用了一个位于线程描述结构(_pthread_descr_struct)中的二维void *指针数组来存放与key关联的数据,数组大小由以下几个宏来说明:

  1. #define PTHREAD_KEY_2NDLEVEL_SIZE       32  
  2. #define PTHREAD_KEY_1STLEVEL_SIZE   /  
  3. ((PTHREAD_KEYS_MAX + PTHREAD_KEY_2NDLEVEL_SIZE - 1)  
  4. / PTHREAD_KEY_2NDLEVEL_SIZE)  
  5. //其中在/usr/include/bits/local_lim.h中定义了PTHREAD_KEYS_MAX为1024,  
  6. //因此一维数组大小为32。而具体存放的位置由key值经过以下计算得到:  
  7. idx1st = key / PTHREAD_KEY_2NDLEVEL_SIZE;  
  8. idx2nd = key % PTHREAD_KEY_2NDLEVEL_SIZE;  

 

也就是说,数据存放与一个32×32的稀疏矩阵中 。同样,访问的时候也由key值经过类似计算得到数据所在位置索引,再取出其中内容返回。(说的更为简单一点就是把一个一维数组模拟成为二维数组,通过除法得到属于哪一层,通过取余运算得到属于该层的第几个元素 ,上述代码中一维长度的计算式为(1024+32-1)/32=static_cast<int>(32.9)=32 )

 

使用范例

以下这个例子没有什么实际意义,只是说明如何使用,以及能够使用这一机制达到存储线程私有数据的目的。

 

  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. pthread_key_t   key;  
  4. void echomsg(int t)  
  5. {  
  6.         printf("destructor excuted in thread %d,param=%d/n",pthread_self(),t);  
  7. }  
  8. void * child1(void *arg)  
  9. {  
  10.         int tid=pthread_self();  
  11.         printf("thread %d enter/n",tid);  
  12.         pthread_setspecific(key,(void *)tid);  
  13.         sleep(2);  
  14.         printf("thread %d returns %d/n",tid,pthread_getspecific(key));  
  15.         sleep(5);  
  16. }  
  17. void * child2(void *arg)  
  18. {  
  19.         int tid=pthread_self();  
  20.         printf("thread %d enter/n",tid);  
  21.         pthread_setspecific(key,(void *)tid);  
  22.         sleep(1);  
  23.         printf("thread %d returns %d/n",tid,pthread_getspecific(key));  
  24.         sleep(5);  
  25. }  
  26. int main(void)  
  27. {  
  28.         int tid1,tid2;  
  29.         printf("hello/n");  
  30.         pthread_key_create(&key,echomsg);  
  31.         pthread_create(&tid1,NULL,child1,NULL);  
  32.         pthread_create(&tid2,NULL,child2,NULL);  
  33.         sleep(10);  
  34.         pthread_key_delete(key);  
  35.         printf("main thread exit/n");  
  36.         return 0;  
  37. }  

 

给例程创建两个线程分别设置同一个线程私有数据为自己的线程ID,为了检验其私有性,程序错开了两个线程私有数据的写入和读出的时间,从程序运行结果可以看出,两个线程对TSD的修改互不干扰。同时,当线程退出时,清理函数会自动执行,参数为tid。

 

上述的程序不太能运行,主要是一些参数转换的问题,可能是我用G++编译的原因。


另外,pthread_t和pthread_key_t的底层类型如下:

typedef unsigned long int pthread_t;

typedef unsigned int pthread_key_t;

 

我调试通过的代码如下:

 

  1. #include<stdio.h>  
  2. #include<pthread.h>  
  3. #include<unistd.h>  
  4. pthread_key_t key;  
  5. //here t is used as int  
  6. void EchoMsg(void* t)  
  7. {  
  8.     printf("Destructor executed in thread %d, param = %d/n",  
  9.             (int)pthread_self(),(int)t);  
  10. }  
  11. void* Child1(void *argv)  
  12. {  
  13.     int tid = pthread_self();  
  14.     printf("thread %d enter/n",tid);  
  15.     pthread_setspecific(key,(void*)(tid));  
  16.     sleep(2);  
  17.     printf("thread %d returns %d/n",tid,(int)pthread_getspecific(key));  
  18.     sleep(5);  
  19. }  
  20. void* Child2(void *argv)  
  21. {  
  22.     pthread_t tid = pthread_self();  
  23.     printf("thread %d enter/n",(int)tid);  
  24.     pthread_setspecific(key,(void*)(tid));  
  25.     sleep(1);  
  26.     printf("thread %d returns %d/n",(int)tid,(int)pthread_getspecific(key));  
  27.     sleep(5);         
  28. }  
  29. int main()  
  30. {  
  31.     //pthread_t的底层设置为typedef unsigned int pthread_t  
  32.     pthread_t tid1,tid2;  
  33.     printf("Hello!/n");  
  34.     pthread_key_create(&key,EchoMsg);  
  35.     pthread_create(&tid1,NULL,Child1,NULL);  
  36.     pthread_create(&tid2,NULL,Child2,NULL);  
  37.     sleep(10);  
  38.     pthread_key_delete(key);  
  39.     printf("Main thread exit/n");  
  40.     return 0;  
  41. }  


在此严重感谢原文作者,原文的链接在本文的开始处。如果要转载请标注原文作者信息。

(文中标为红色的为个人认为重要的部分,蓝色的是我自己的笔记)

 

P.S. long int 在我的32位机器下的长度为4,和int的长度一致(long long的长度为8)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值