POSIX线程专有数据的空间释放问题,pthread_key_create
下面说一下线程中特有的线程存储, 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*));下面是一个如何使用线程存储的例子:
- <pre name="code" class="cpp">#include <malloc.h>
- #include <pthread.h>
- #include <stdio.h>
- /* The key used to associate a log file pointer with each thread. */
- static pthread_key_t thread_log_key;
- /* Write MESSAGE to the log file for the current thread. */
- void write_to_thread_log (const char* message)
- {
- FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key);
- fprintf (thread_log, “%s\n”, message);
- }
- /* Close the log file pointer THREAD_LOG. */
- void close_thread_log (void* thread_log)
- {
- fclose ((FILE*) thread_log);
- }
- void* thread_function (void* args)
- {
- char thread_log_filename[20];
- FILE* thread_log;
- /* Generate the filename for this thread’s log file. */
- sprintf (thread_log_filename, “thread%d.log”, (int) pthread_self ());
- /* Open the log file. */
- thread_log = fopen (thread_log_filename, “w”);
- /* Store the file pointer in thread-specific data under thread_log_key. */
- pthread_setspecific (thread_log_key, thread_log);
- write_to_thread_log (“Thread starting.”);
- /* Do work here... */
- return NULL;
- }
- int main ()
- {
- int i;
- pthread_t threads[5];
- /* Create a key to associate thread log file pointers in
- thread-specific data. Use close_thread_log to clean up the file
- pointers. */
- pthread_key_create (&thread_log_key, close_thread_log);
- /* Create threads to do the work. */
- for (i = 0; i < 5; ++i)
- pthread_create (&(threads[i]), NULL, thread_function, NULL);
- /* Wait for all threads to finish. */
- for (i = 0; i < 5; ++i)
- pthread_join (threads[i], NULL);
- return 0;
- } </pre><br><br>
最后说一下线程的本质。其实在Linux 中,新建的线程并不是在原先的进程中,而是系统通过一个系统调用clone() 。该系统copy 了一个和原先进程完全一样的进程,并在这个进程中执行线程函数。不过这个copy 过程和fork 不一样。copy 后的进程和原先的进程共享了所有的变量,运行环境。这样,原先进程中的变量变动在copy 后的进程中便能体现出来
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------/先记下来,以后有机会请教高手
我使用的测试程序:
- #include <pthread.h >
- #include <stdio.h >
- #include <unistd.h >
- using namespace std;
- pthread_key_t key;
- void echomsg(void* p)
- {
- int t=*(int*)p;
- printf( "destructor excuted in thread %d, param=%d\n ",pthread_self(),t);
- }
- void* child1(void* arg)
- {
- int*ptid= new int;
- *ptid=pthread_self();
- printf( "thread %d enter\n ",*ptid);
- pthread_setspecific(key,(void*)ptid);
- sleep(2);
- printf( "thread %d returns %d\n ",*ptid,*((int*)pthread_getspecific(key)));
- sleep(5);
- pthread_exit(NULL);
- return NULL;
- }
- void* child2(void* arg)
- {
- int*ptid= new int;
- *ptid=pthread_self();
- printf( "thread %d enter\n ",*ptid);
- pthread_setspecific(key,(void*)ptid);
- sleep(1);
- printf( "thread %d returns %d\n ",*ptid,*((int*)pthread_getspecific(key)));
- sleep(5);
- pthread_exit(NULL);
- return NULL;
- }
- int main()
- {
- pthread_t tid1,tid2;
- printf( "hello\n ");
- pthread_key_create(&key,echomsg);
- pthread_create(&tid1,NULL,child1,NULL);
- pthread_create(&tid2,NULL,child2,NULL);
- //pthread_join(tid1,NULL);
- pthread_join(tid2,NULL);
- sleep(3);
- pthread_key_delete(key);
- printf( "main thread %d exit\n ",pthread_self());
- return 0;
- }
这是程序输出
----------------------------------------------
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,自己改进的代码如下:
- #include <pthread.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h> //atexit
- using namespace std;
- pthread_key_t key;
- pthread_once_t thread_once = PTHREAD_ONCE_INIT;
- void echomsg(void *);
- void once_run(void)
- {
- printf("pthread_key_t init in the once_run\n ");
- pthread_key_create(&key,echomsg);
- }
- void echomsg(void* p)
- {
- int t=*(int*)p;
- printf( "destructor excuted in thread %d, param=%d\n ",pthread_self(),t);
- delete (int *)p;
- }
- void* child1(void* arg)
- {
- int*ptid= new int;
- pthread_once(&thread_once, once_run);//测试pthread_once是否还会在此执行不,因为在main线程已经执行了.
- *ptid=pthread_self();
- printf( "thread1 %d enter\n ",*ptid);
- pthread_setspecific(key,(void*)ptid);
- sleep(2);
- printf( "thread1 %d returns %d\n ",*ptid,*((int*)pthread_getspecific(key)));
- sleep(5);
- pthread_exit(NULL);
- return NULL;
- }
- void* child2(void* arg)
- {
- int*ptid= new int;
- *ptid=pthread_self();
- printf( "thread2 %d enter\n ",*ptid);
- pthread_setspecific(key,(void*)ptid);
- sleep(1);
- printf( "thread2 %d returns %d\n ",*ptid,*((int*)pthread_getspecific(key)));
- sleep(1);
- pthread_exit(NULL);
- return NULL;
- }
- void main_exit()
- {
- pthread_key_delete(key);
- }
- int main()
- {
- pthread_t tid1,tid2;
- printf( "hello\n ");
- atexit(main_exit);//为了防止sleep(4)放到pthread_key_delete(key)后面就会出现段错误了。但是个人也不很提倡用atexit这个函数。
- pthread_once(&thread_once, once_run);
- //pthread_key_create(&key,echomsg); //保证一次性运行把其放到了pthread_once了
- pthread_create(&tid1,NULL,child1,NULL);
- pthread_create(&tid2,NULL,child2,NULL);
- //pthread_join(tid1,NULL);
- //pthread_join(tid2,NULL);
- sleep(3);
- //pthread_key_delete(key);
- printf( "main thread %d exit\n ",pthread_self());
- return 0;
- }
程序输出:
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相关推荐
- TSD(Thread Specific Data)线程专有数据
(1)全局变量 (2)局部变量 (3)TSD(Thread-Specific Data 线程专有数据) 1.http://upczap.itpub.net/ 在单线程的程序里,有两种基本的数据:全局变 ...
- MySQL 的几种碎片整理方案总结(解决delete大量数据后空间不释放的问题)
MySQL 的几种碎片整理方案总结(解决delete大量数据后空间不释放的问题) 1.背景知识 1.1 为什么会有碎片 MySQL 中 insert 与 update 都可能导致页分裂,这样就存在碎片 ...
- mysql删除数据后多久释放空间
mysql 在删除大量表数据时怎么释放空间 能说详细点吗?指的是底层的数据怎么释放?还是SQL语句执行drop table,delete from等语句的流程?写个程序,或者过程 , delete 或 ...
- Mysql在生产环境中快速清理数据及表空间释放
Mysql数据快速清理及表空间释放 1.TABLES表主要字段说明: MySQL的 information_schema 数据库中的TABLES 表记录了MySQL数据库中每个表占用的空间.表记录的行 ...
- Linux系统编程——线程私有数据
在多线程程序中.常常要用全局变量来实现多个函数间的数据共享.因为数据空间是共享的,因此全局变量也为全部线程共同拥有. 測试代码例如以下: #include <stdio.h> #inclu ...
- 【Linux系统编程】线程私有数据
00. 目录 文章目录 00. 目录 01. 线程之间共享数据 02. 线程私有数据 2.1 创建线程私有数据 2.2 销毁线程私有数据 2.3 关联线程私有数据成员 2.4 读取线程私有数据所关联的 ...
- POSIX线程的同步
当线程运行在同样的线程空间,线程们共享同样的内存和资源.这使它变得很容易对于线程来通信和共享数据,尽管它会发生两种问题:线程阻塞和内存不一致由于线程的同步对共享资源的修改.在这些情况下,线程同步变得很 ...
- Linux多线程实践(4) --线程特定数据
线程特定数据 int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *)); int pthread_key_ ...
- posix线程使用详解
原文:http://blog.csdn.net/liuhongxiangm/article/details/8308697 Posix多线程编程学习笔记(一)-线程基础(1) 一.什么是线程 ...
最新文章
- 分布式概念-去中心化副本控制实现
- .bat文件(%~dp0)和call、echo批处理环境变量
- Linux内核:关于中断你需要知道的【转】
- 在千万级的数据库查询中,如何提高效率?
- CLR查找和加载程序集的方式(二) 流程图
- 使用Java从地图中删除元素
- 两个变量实现查找坏环c语言,C/C++编程笔记:C语言编程知识要点总结!大一C语言知识点(全)...
- linux路由内核实现分析(四)---路由缓存机制(3)
- 第9章 SportsStorePeta 完成购物车
- Java I/O系统之处理流类型
- 【机器学习系列】变分推断第二讲:基于Mean Field的变分推断解法
- 小福利,excel的常用高阶函数介绍
- 6678学习笔记开篇
- postman文件导入
- 【人工智能】【1024】谷歌量子计算突破登Nature封面,号称200秒顶超算10000年!
- 511遇见易语言子程序参考的作用
- Unity 大面积草风吹动效果+受人物影响
- SystemVerilog与功能验证
- 【Linux命令行与Shell脚本编程】三,Linux文件系统
- ios应用白名单打包
热门文章
- 鸿蒙系统-手机-HAP开发编译调试
- android 如何 查看内存使用详情,android 查看内存使用情况
- django解决NameError: name ‘_mysql‘ is not defined 或 mysqlclient 1.4.0 or newer is required报错
- pytorch学习——构建多元线性回归的网络结构
- mysql默认存储引擎的索引结构是_InnoDB引擎的索引和存储结构
- Codeforces.700E.Cool Slogans(后缀自动机 线段树合并 DP)
- LIB和DLL的区别与使用
- Linux 系统之Sysvinit
- modelsim不停出现loading……无法仿真
- bcp生成excel文件优化方案