下面说一下线程中特有的线程存储, 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*));下面是一个如何使用线程存储的例子:
[cpp] view plaincopy
  1. <pre name="code" class="cpp">#include <malloc.h>
  2. #include <pthread.h>
  3. #include <stdio.h>
  4. /* The key used to associate a log file pointer with each thread. */
  5. static pthread_key_t thread_log_key;
  6. /* Write MESSAGE to the log file for the current thread. */
  7. void write_to_thread_log (const char* message)
  8. {
  9. FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key);
  10. fprintf (thread_log, “%s\n”, message);
  11. }
  12. /* Close the log file pointer THREAD_LOG. */
  13. void close_thread_log (void* thread_log)
  14. {
  15. fclose ((FILE*) thread_log);
  16. }
  17. void* thread_function (void* args)
  18. {
  19. char thread_log_filename[20];
  20. FILE* thread_log;
  21. /* Generate the filename for this thread’s log file. */
  22. sprintf (thread_log_filename, “thread%d.log”, (int) pthread_self ());
  23. /* Open the log file. */
  24. thread_log = fopen (thread_log_filename, “w”);
  25. /* Store the file pointer in thread-specific data under thread_log_key. */
  26. pthread_setspecific (thread_log_key, thread_log);
  27. write_to_thread_log (“Thread starting.”);
  28. /* Do work here... */
  29. return NULL;
  30. }
  31. int main ()
  32. {
  33. int i;
  34. pthread_t threads[5];
  35. /* Create a key to associate thread log file pointers in
  36. thread-specific data. Use close_thread_log to clean up the file
  37. pointers. */
  38. pthread_key_create (&thread_log_key, close_thread_log);
  39. /* Create threads to do the work. */
  40. for (i = 0; i < 5; ++i)
  41. pthread_create (&(threads[i]), NULL, thread_function, NULL);
  42. /* Wait for all threads to finish. */
  43. for (i = 0; i < 5; ++i)
  44. pthread_join (threads[i], NULL);
  45. return 0;
  46. }  </pre><br><br>
最后说一下线程的本质。其实在Linux 中,新建的线程并不是在原先的进程中,而是系统通过一个系统调用clone() 。该系统copy 了一个和原先进程完全一样的进程,并在这个进程中执行线程函数。不过这个copy 过程和fork 不一样。copy 后的进程和原先的进程共享了所有的变量,运行环境。这样,原先进程中的变量变动在copy 后的进程中便能体现出来
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------/先记下来,以后有机会请教高手



最近学习通过pthread_key_create创建的线程专有数据时发现如果不对线程使用pthread_join,则不会调用pthread_key_create所指定的资源释放函数。而并没有像书上所说的在线程pthread_exit()后就会调用释放函数。这是为什么?究竟什么情况下会调用?
我使用的测试程序:
[cpp] view plaincopy
  1. #include <pthread.h >
  2. #include <stdio.h >
  3. #include <unistd.h >
  4. using namespace std;
  5. pthread_key_t key;
  6. void echomsg(void* p)
  7. {
  8. int t=*(int*)p;
  9. printf( "destructor excuted in thread %d, param=%d\n ",pthread_self(),t);
  10. }
  11. void* child1(void* arg)
  12. {
  13. int*ptid= new int;
  14. *ptid=pthread_self();
  15. printf( "thread %d enter\n ",*ptid);
  16. pthread_setspecific(key,(void*)ptid);
  17. sleep(2);
  18. printf( "thread %d returns %d\n ",*ptid,*((int*)pthread_getspecific(key)));
  19. sleep(5);
  20. pthread_exit(NULL);
  21. return NULL;
  22. }
  23. void* child2(void* arg)
  24. {
  25. int*ptid= new int;
  26. *ptid=pthread_self();
  27. printf( "thread %d enter\n ",*ptid);
  28. pthread_setspecific(key,(void*)ptid);
  29. sleep(1);
  30. printf( "thread %d returns %d\n ",*ptid,*((int*)pthread_getspecific(key)));
  31. sleep(5);
  32. pthread_exit(NULL);
  33. return NULL;
  34. }
  35. int main()
  36. {
  37. pthread_t tid1,tid2;
  38. printf( "hello\n ");
  39. pthread_key_create(&key,echomsg);
  40. pthread_create(&tid1,NULL,child1,NULL);
  41. pthread_create(&tid2,NULL,child2,NULL);
  42. //pthread_join(tid1,NULL);
  43. pthread_join(tid2,NULL);
  44. sleep(3);
  45. pthread_key_delete(key);
  46. printf( "main thread %d exit\n ",pthread_self());
  47. return 0;
  48. }

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

程序输出:

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.csdn.net/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);

}

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

  1. TSD(Thread Specific Data)线程专有数据

    (1)全局变量 (2)局部变量 (3)TSD(Thread-Specific Data 线程专有数据) 1.http://upczap.itpub.net/ 在单线程的程序里,有两种基本的数据:全局变 ...

  2. MySQL 的几种碎片整理方案总结(解决delete大量数据后空间不释放的问题)

    MySQL 的几种碎片整理方案总结(解决delete大量数据后空间不释放的问题) 1.背景知识 1.1 为什么会有碎片 MySQL 中 insert 与 update 都可能导致页分裂,这样就存在碎片 ...

  3. mysql删除数据后多久释放空间

    mysql 在删除大量表数据时怎么释放空间 能说详细点吗?指的是底层的数据怎么释放?还是SQL语句执行drop table,delete from等语句的流程?写个程序,或者过程 , delete 或 ...

  4. Mysql在生产环境中快速清理数据及表空间释放

    Mysql数据快速清理及表空间释放 1.TABLES表主要字段说明: MySQL的 information_schema 数据库中的TABLES 表记录了MySQL数据库中每个表占用的空间.表记录的行 ...

  5. Linux系统编程——线程私有数据

    在多线程程序中.常常要用全局变量来实现多个函数间的数据共享.因为数据空间是共享的,因此全局变量也为全部线程共同拥有. 測试代码例如以下: #include <stdio.h> #inclu ...

  6. 【Linux系统编程】线程私有数据

    00. 目录 文章目录 00. 目录 01. 线程之间共享数据 02. 线程私有数据 2.1 创建线程私有数据 2.2 销毁线程私有数据 2.3 关联线程私有数据成员 2.4 读取线程私有数据所关联的 ...

  7. POSIX线程的同步

    当线程运行在同样的线程空间,线程们共享同样的内存和资源.这使它变得很容易对于线程来通信和共享数据,尽管它会发生两种问题:线程阻塞和内存不一致由于线程的同步对共享资源的修改.在这些情况下,线程同步变得很 ...

  8. Linux多线程实践(4) --线程特定数据

    线程特定数据 int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *)); int pthread_key_ ...

  9. posix线程使用详解

     原文:http://blog.csdn.net/liuhongxiangm/article/details/8308697 Posix多线程编程学习笔记(一)-线程基础(1) 一.什么是线程   ...

最新文章

  1. 分布式概念-去中心化副本控制实现
  2. .bat文件(%~dp0)和call、echo批处理环境变量
  3. Linux内核:关于中断你需要知道的【转】
  4. 在千万级的数据库查询中,如何提高效率?
  5. CLR查找和加载程序集的方式(二) 流程图
  6. 使用Java从地图中删除元素
  7. 两个变量实现查找坏环c语言,C/C++编程笔记:C语言编程知识要点总结!大一C语言知识点(全)...
  8. linux路由内核实现分析(四)---路由缓存机制(3)
  9. 第9章 SportsStorePeta 完成购物车
  10. Java I/O系统之处理流类型
  11. 【机器学习系列】变分推断第二讲:基于Mean Field的变分推断解法
  12. 小福利,excel的常用高阶函数介绍
  13. 6678学习笔记开篇
  14. postman文件导入
  15. 【人工智能】【1024】谷歌量子计算突破登Nature封面,号称200秒顶超算10000年!
  16. 511遇见易语言子程序参考的作用
  17. Unity 大面积草风吹动效果+受人物影响
  18. SystemVerilog与功能验证
  19. 【Linux命令行与Shell脚本编程】三,Linux文件系统
  20. ios应用白名单打包

热门文章

  1. 鸿蒙系统-手机-HAP开发编译调试
  2. android 如何 查看内存使用详情,android 查看内存使用情况
  3. django解决NameError: name ‘_mysql‘ is not defined 或 mysqlclient 1.4.0 or newer is required报错
  4. pytorch学习——构建多元线性回归的网络结构
  5. mysql默认存储引擎的索引结构是_InnoDB引擎的索引和存储结构
  6. Codeforces.700E.Cool Slogans(后缀自动机 线段树合并 DP)
  7. LIB和DLL的区别与使用
  8. Linux 系统之Sysvinit
  9. modelsim不停出现loading……无法仿真
  10. bcp生成excel文件优化方案