线程特定数据函数的使用
2013-01-08 19:31
323 查看
《APUE》 12.6节
线程特定数据(或线程私有数据,TSD) 的学习
建议参考《unix网络编程卷1》的第26.5节来看,它讲得更加详细。
练习代码如下:
可以看到在thread 1234执行了pthread_key_delete()之后,不仅切断了thread 1234与其线程特定数据之间的联系,而且也切断了thread 5678与其线程特定数据之间的联系。
线程特定数据(或线程私有数据,TSD) 的学习
建议参考《unix网络编程卷1》的第26.5节来看,它讲得更加详细。
练习代码如下:
#include "apue.h" #include <pthread.h> static pthread_key_t r_key; static pthread_once_t r_once = PTHREAD_ONCE_INIT; void free_buf(void * buf) { free(buf); } void key_init(void) { pthread_key_create(&r_key,free_buf); } void * operation(void * thread_num) { int num = (int)thread_num; pthread_detach(pthread_self()); pthread_once(&r_once,key_init); int * data; if(pthread_getspecific(r_key) == NULL) { printf("malloc:\n"); data = (int *)malloc(sizeof(int)); pthread_setspecific(r_key,data); *data = num; } printf("the specific data of Thread %d is %d\n",num, *((int *)pthread_getspecific(r_key))); if(num == 1234) { sleep(5);// 让5678进程能够执行到sleep 10s pthread_key_delete(r_key); }else { // 让1234进程能够执行到sleep 5,delete key sleep(10); } if(pthread_getspecific(r_key) != NULL) { printf("-----the specific data of Thread %d is %d\n",num, *((int *)pthread_getspecific(r_key))); }else { printf("---- the Thread num is %d, and it have no specific data \n",num); } pthread_exit(NULL); return((void *)0); } int main() { pthread_t tid1,tid2; int err = 0; err = pthread_create(&tid1,NULL,operation,(void *)1234); if(err != 0) { printf("can not crate thread 1\n"); return -1; } err = pthread_create(&tid2,NULL,operation,(void *)5678); if(err != 0) { printf("can not crate thread 2\n"); return -1; } sleep(20);//等待线程打印结果 return 0; }
可以看到在thread 1234执行了pthread_key_delete()之后,不仅切断了thread 1234与其线程特定数据之间的联系,而且也切断了thread 5678与其线程特定数据之间的联系。
相关文章推荐
- 在类中使用_beginthreadex函数创建线程并访问该类中的数据成员
- LInux多线程编程----线程特定数据的处理函数
- C#中的多线程使用 -- Thread 类: 使用回调函数从一个线程中检索数据
- Linux多线程实践(4) --线程特定数据
- boost::thread 使用函数对象来构造线程对象的问题
- 使用管道流和多线程完成以下任务要求: 一个线程对象t1 会从控制台中不停的读取信息,读到之后把数据交给管道输出流,把数据写到管道里面 ,另一个线程对象t2 不停的使用管道输入流从管道
- 在界面线程不能使用Sleep和WaitForSingleObject之类的函数, 使用 MsgWaitForMultipleObjects
- 基于curl数据采集之单页面并行采集函数get_htmls的使用
- oracle 中合并数据 wm_concat(column)函数的使用
- 线程同时执行一个函数 使用临界区 14.4.29
- 线程函数的设计以及MsgWaitForMultipleObjects函数的使用要点 ----- 转
- 使用ThreadLocal在线程内部传递数据
- spark-sql使用UDF函数实现ip映射省份,数据写出到mysql参数设置。
- 【黑马Android】(05)短信/查询和添加/内容观察者使用/子线程网络图片查看器和Handler消息处理器/html查看器/使用HttpURLConnection采用Post方式请求数据/开源项目
- 使用HttpSendRequest函数POST数据时应该注意的一点
- JAVA入门.零基础学Java语言 MOOC 第6周 使用对象(基本数据类型的包裹类型对象) 第7周 函数
- Java多线程之~~~使用Exchanger在线程之间交换数据[这个结合多线程并行会有解决很多问题]生产者消费者模型
- 线程函数的设计以及MsgWaitForMultipleObjects函数的使用要点
- AJax的使用json数据的传输回调函数
- hive 到表之间加复制数据 和 hdfs上表导入本地数据 和本地数据导入到 hdfs上表中,和函数的使用