POSIX线程专有数据的空间释放问题,pthread_key_create

本文详细介绍了线程存储(Thread Specific Data)的概念及其在多线程程序中的作用,重点解析了pthread_key_create等函数的使用方法,并通过示例程序展示了如何正确使用线程专有数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面说一下线程中特有的线程存储, Thread Specific Data 。线程存储有什么用了?他是什么意思了?大家都知道,在多线程程序中,所有线程共享程序中的变量。现在有一全局变量,所有线程都可以使用它,改变它的值。而如果每个线程希望能单独拥有它,那么就需要使用线程存储了。表面上看起来这是一个全局变量,所有线程都可以使用它,而它的值在每一个线程中又是单独存储的。这就是线程存储的意义。

下面说一下线程存储的具体用法。

l          创建一个类型为 pthread_key_t 类型的变量。

l          调用 pthread_key_create() 来创建该变量。该函数有两个参数,第一个参数就是上面声明的 pthread_key_t 变量,第二个参数是一个清理函数,用来在线程释放该线程存储的时候被调用。该函数指针可以设成 NULL ,这样系统将调用默认的清理函数。

l          当线程中需要存储特殊值的时候,可以调用 pthread_setspcific() 。该函数有两个参数,第一个为前面声明的 pthread_key_t 变量,第二个为 void* 变量,这样你可以存储任何类型的值。

l          如果需要取出所存储的值,调用 pthread_getspecific() 。该函数的参数为前面提到的 pthread_key_t 变量,该函数返回 void * 类型的值。

下面是前面提到的函数的原型:

int pthread_setspecific(pthread_key_t key, const void *value);

void *pthread_getspecific(pthread_key_t key);

int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));

下面是一个如何使用线程存储的例子:

  
  1. <pre name="code" class="cpp">#include <malloc.h>  
  2.   
  3. #include <pthread.h>  
  4.   
  5. #include <stdio.h>  
  6.   
  7. /* The key used to associate a log file pointer with each thread. */  
  8.   
  9. static pthread_key_t thread_log_key;  
  10.   
  11. /* Write MESSAGE to the log file for the current thread. */  
  12.   
  13. void write_to_thread_log (const char* message)  
  14.   
  15. {  
  16.   
  17. FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key);  
  18.   
  19. fprintf (thread_log, “%s\n”, message);  
  20.   
  21. }  
  22.   
  23. /* Close the log file pointer THREAD_LOG. */  
  24.   
  25. void close_thread_log (void* thread_log)  
  26.   
  27. {  
  28.   
  29. fclose ((FILE*) thread_log);  
  30.   
  31. }  
  32.   
  33. void* thread_function (void* args)  
  34.   
  35. {  
  36.   
  37. char thread_log_filename[20];  
  38.   
  39. FILE* thread_log;  
  40.   
  41. /* Generate the filename for this thread’s log file. */  
  42.   
  43. sprintf (thread_log_filename, “thread%d.log”, (int) pthread_self ());  
  44.   
  45. /* Open the log file. */  
  46.   
  47. thread_log = fopen (thread_log_filename, “w”);  
  48.   
  49. /* Store the file pointer in thread-specific data under thread_log_key. */  
  50.   
  51. pthread_setspecific (thread_log_key, thread_log);  
  52.   
  53. write_to_thread_log (“Thread starting.”);  
  54.   
  55. /* Do work here... */  
  56.   
  57. return NULL;  
  58.   
  59. }  
  60.   
  61. int main ()  
  62.   
  63. {  
  64.   
  65. int i;  
  66.   
  67. pthread_t threads[5];  
  68.   
  69. /* Create a key to associate thread log file pointers in 
  70.  
  71. thread-specific data. Use close_thread_log to clean up the file 
  72.  
  73. pointers. */  
  74.   
  75. pthread_key_create (&thread_log_key, close_thread_log);  
  76.   
  77. /* Create threads to do the work. */  
  78.   
  79. for (i = 0; i < 5; ++i)  
  80.   
  81. pthread_create (&(threads[i]), NULL, thread_function, NULL);  
  82.   
  83. /* Wait for all threads to finish. */  
  84.   
  85. for (i = 0; i < 5; ++i)  
  86.   
  87. pthread_join (threads[i], NULL);  
  88.   
  89. return 0;  
  90.   
  91. }  </pre><br><br>  
最后说一下线程的本质。其实在Linux 中,新建的线程并不是在原先的进程中,而是系统通过一个系统调用clone() 。该系统copy 了一个和原先进程完全一样的进程,并在这个进程中执行线程函数。不过这个copy 过程和fork 不一样。copy 后的进程和原先的进程共享了所有的变量,运行环境。这样,原先进程中的变量变动在copy 后的进程中便能体现出来
//////--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------/////先记下来,以后有机会请教高手



最近学习通过pthread_key_create创建的线程专有数据时发现如果不对线程使用pthread_join,则不会调用pthread_key_create所指定的资源释放函数。而并没有像书上所说的在线程pthread_exit()后就会调用释放函数。这是为什么?究竟什么情况下会调用?
我使用的测试程序:

[cpp]  view plain copy
  1. #include <pthread.h >   
  2. #include <stdio.h >   
  3. #include <unistd.h >   
  4.   
  5. using namespace std;   
  6.   
  7. pthread_key_t key;   
  8. void echomsg(void* p)   
  9. {   
  10. int t=*(int*)p;   
  11. printf( "destructor excuted in thread %d, param=%d\n ",pthread_self(),t);   
  12. }   
  13.   
  14. void* child1(void* arg)   
  15. {   
  16. int*ptid= new int;   
  17. *ptid=pthread_self();   
  18. printf( "thread %d enter\n ",*ptid);   
  19. pthread_setspecific(key,(void*)ptid);   
  20. sleep(2);   
  21. printf( "thread %d returns %d\n ",*ptid,*((int*)pthread_getspecific(key)));   
  22. sleep(5);   
  23. pthread_exit(NULL);   
  24. return NULL;   
  25. }   
  26.   
  27. void* child2(void* arg)   
  28. {   
  29. int*ptid= new int;   
  30. *ptid=pthread_self();   
  31. printf( "thread %d enter\n ",*ptid);   
  32. pthread_setspecific(key,(void*)ptid);   
  33. sleep(1);   
  34. printf( "thread %d returns %d\n ",*ptid,*((int*)pthread_getspecific(key)));   
  35. sleep(5);   
  36. pthread_exit(NULL);   
  37. return NULL;   
  38. }   
  39.   
  40. int main()   
  41. {   
  42. pthread_t tid1,tid2;   
  43. printf( "hello\n ");   
  44. pthread_key_create(&key,echomsg);   
  45. pthread_create(&tid1,NULL,child1,NULL);   
  46. pthread_create(&tid2,NULL,child2,NULL);   
  47. //pthread_join(tid1,NULL);   
  48. pthread_join(tid2,NULL);   
  49. sleep(3);   
  50. pthread_key_delete(key);   
  51. printf( "main thread %d exit\n ",pthread_self());   
  52.   
  53. return 0;   
  54. }   



这是程序输出 
---------------------------------------------- 
hello 
thread  1083395264  enter 
thread  1091783744  enter 
thread  1091783744  returns  1091783744 
thread  1083395264  returns  1083395264 
destructor  excuted  in  thread  1075005312,  param=1091783744
main  thread  1075005312  exit 

----------------------------------------------
 

         这是在网上看到的一篇文章,个人认为并不是pthread_join接受线程时才调用每个线程的key的echomsg函数。而是由于pthread_join阻塞等待特定的线程结束,以至于被等待的线程能够全部处理完(当然包括每个线程key的特定清理函数echomsg),所以当pthread_join尤其用在main线程中时,能够确保特定的子线程能处理完。

       在以上程序中,稍加修改:child2()函数中的sleep睡眠时间都改为sleep(1),并且把主函数的pthread_join(tid2,NULL);也注释掉,重新编译执行也会得到上面类似的结果。

       同时也发现child1的线程也退出了,并没有sleep(5)足够的时间,我认为是child2线程结束时要发送信号,而sleep是可被信号中断的(这个陈述稍有欠当,姑且是那个意思),所以child1的线程在child2结束后也结束了。但是没来及执行child1的echomsg,main线程就结束了,随之整个进程也结束了

个人认为上面的程序有点隐形的bug,自己改进的代码如下:

 

[cpp]  view plain copy
  1. #include    <pthread.h>    
  2. #include    <stdio.h>    
  3. #include    <unistd.h>    
  4. #include    <stdlib.h> //atexit  
  5.   
  6. using  namespace  std;    
  7.   
  8. pthread_key_t  key;    
  9. pthread_once_t thread_once = PTHREAD_ONCE_INIT;  
  10.   
  11. void echomsg(void *);  
  12. void once_run(void)  
  13. {  
  14.     printf("pthread_key_t init in the once_run\n  ");  
  15.     pthread_key_create(&key,echomsg);  
  16.   
  17. }  
  18. void  echomsg(void*  p)    
  19. {    
  20.     int  t=*(int*)p;    
  21.     printf(  "destructor  excuted  in  thread  %d,  param=%d\n  ",pthread_self(),t);    
  22.     delete (int *)p;  
  23. }    
  24.   
  25. void*  child1(void*  arg)    
  26. {    
  27.     int*ptid=  new  int;    
  28.   
  29.     pthread_once(&thread_once, once_run);//测试pthread_once是否还会在此执行不,因为在main线程已经执行了.  
  30.     *ptid=pthread_self();    
  31.     printf(  "thread1  %d  enter\n  ",*ptid);    
  32.     pthread_setspecific(key,(void*)ptid);    
  33.     sleep(2);    
  34.     printf(  "thread1  %d  returns  %d\n  ",*ptid,*((int*)pthread_getspecific(key)));    
  35.     sleep(5);    
  36.     pthread_exit(NULL);    
  37.     return  NULL;    
  38. }    
  39.   
  40. void*  child2(void*  arg)    
  41. {    
  42.     int*ptid=  new  int;    
  43.     *ptid=pthread_self();    
  44.     printf(  "thread2  %d  enter\n  ",*ptid);    
  45.     pthread_setspecific(key,(void*)ptid);    
  46.     sleep(1);    
  47.     printf(  "thread2  %d  returns  %d\n  ",*ptid,*((int*)pthread_getspecific(key)));    
  48.     sleep(1);    
  49.     pthread_exit(NULL);    
  50.     return  NULL;    
  51. }    
  52.   
  53. void main_exit()  
  54. {  
  55.     pthread_key_delete(key);  
  56.   
  57. }  
  58. int  main()    
  59. {    
  60.     pthread_t  tid1,tid2;    
  61.     printf(  "hello\n  ");    
  62.     atexit(main_exit);//为了防止sleep(4)放到pthread_key_delete(key)后面就会出现段错误了。但是个人也不很提倡用atexit这个函数。  
  63.     pthread_once(&thread_once, once_run);  
  64.     //pthread_key_create(&key,echomsg);  //保证一次性运行把其放到了pthread_once了  
  65.     pthread_create(&tid1,NULL,child1,NULL);    
  66.     pthread_create(&tid2,NULL,child2,NULL);    
  67.     //pthread_join(tid1,NULL);    
  68.     //pthread_join(tid2,NULL);    
  69.     sleep(3);    
  70.     //pthread_key_delete(key);    
  71.     printf(  "main  thread  %d  exit\n  ",pthread_self());    
  72.   
  73.     return  0;    
  74. }   



程序输出:

hello
  pthread_key_t init in the once_run
  thread1  -1208583280  enter
  thread2  -1219073136  enter
  thread2  -1219073136  returns  -1219073136
  thread1  -1208583280  returns  -1208583280
  destructor  excuted  in  thread  -1219073136,  param=-1219073136
  main  thread  -1208580400  exit

 

-到此结束-睡觉

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

<pthread_once and pthread_key_create的交叉应用说明>

转自:http://blog.youkuaiyun.com/yuyin86/article/details/6735245

 

一次性初始化

    有时候我们需要对一些posix变量只进行一次初始化,如线程键(我下面会讲到)。如果我们进行多次初始化程序就会出现错误。

    在传统的顺序编程中,一次性初始化经常通过使用布尔变量来管理。控制变量被静态初始化为0,而任何依赖于初始化的代码都能测试该变量。如果变量值仍然为0,则它能实行初始化,然后将变量置为1。以后检查的代码将跳过初始化。

    但是在多线程程序设计中,事情就变的复杂的多。如果多个线程并发地执行初始化序列代码,可能有2个线程发现控制变量为0,并且都实行初始化,而该过程本该仅仅执行一次。

如果我们需要对一个posix变量静态的初始化,可使用的方法是用一个互斥量对该变量的初始话进行控制。但有时候我们需要对该变量进行动态初始化,pthread_once就会方便的多。 

函数原形:

pthread_once_t once_control=PTHREAD_ONCE_INIT;

int pthread_once(pthread_once_t *once_control,void(*init_routine)(void));

参数:

once_control         控制变量

init_routine         初始化函数

返回值:

若成功返回0,若失败返回错误编号。

 类型为pthread_once_t的变量是一个控制变量。控制变量必须使用PTHREAD_ONCE_INIT宏静态地初始化。

pthread_once函数首先检查控制变量,判断是否已经完成初始化,如果完成就简单地返回;否则,pthread_once调用初始化函数,并且记录下初始化被完成。如果在一个线程初始时,另外的线程调用pthread_once,则调用线程等待,直到那个现成完成初始话返回。

下面就是该函数的程序例子: 

#include <pthread.h>

pthread_once_t once=PTHREAD_ONCE_INIT;

pthread_mutex_t mutex; 

void once_init_routine(void) 

{

    int status;

    status=pthread_mutex_init(&mutex,NULL);

    if(status==0)

    printf(“Init success!,My id is %u”,pthread_self());

}

void *child_thread(void *arg)

{

    printf(“I’m child ,My id is %u”,pthread_self());

    pthread_once(&once,once_init_routine);

}

    int main(int argc,char *argv[ ])

{

    pthread_t child_thread_id;

    pthread_create(&child_thread_id,NULL,child_thread,NULL);

    printf(“I’m father,my id is %u”,pthread_self());

    pthread_once(&once_block,once_init_routine);

    pthread_join(child_thread_id,NULL);

}

线程的私有数据

    在进程内的所有线程共享相同的地址空间,任何声明为静态或外部的变量,或在进程堆声明的变量,都可以被进程所有的线程读写。那怎样才能使线程序拥有自己的私有数据呢。

posix提供了一种方法,创建线程键。

函数原形:

int pthread_key_create(pthread_key *key,void(*destructor)(void *));

参数:

key           私有数据键

destructor    清理函数

返回值:

若成功返回0,若失败返回错误编号

   第一个参数为指向一个键值的指针,第二个参数指明了一个destructor函数(清理函数),如果这个参数不为空,那么当每个线程结束时,系统将调用这个函数来释放绑定在这个键上的内存块。这个函数常和函数pthread_once一起使用,为了让这个键只被创建一次。函数pthread_once声明一个初始化函数,第一次调用pthread_once时它执行这个函数,以后的调用将被它忽略。

下面是程序例子: 

#include <pthread.h>

pthread_key_t tsd_key;

pthread_once_t key_once=PTHREAD_ONCE_INIT;

void once_routine(void)

{

int status;

status=pthread_key_create(&tsd_key,NULL);

if(status=0)

    printf(“Key create success! My id is %u/n”,pthread_self());

}

void *child_thread(void *arg)

{

printf(“I’m child,My id is %u/n”,pthread_self());

pthread_once(&key_once,once_routine);

}

int main(int argc,char *argv[ ])

{

pthread_t child_thread_id;

pthread_create(&child_thread_id,NULL,child_thread,NULL);

printf(“I’m father,my id is%u/n”,pthread_self());

pthread_once(&key_once,once_routine);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值