pthread_getpecific和pthread_setspecific
2015-07-01 16:47
471 查看
pthread_getpecific和pthread_setspecific实现同一个线程中不同函数间共享数据的一种很好的方式。
#more test.c
/*
* =====================================================================================
* Filename: thead.c
* Description: getspecific
* Created: 05/10/2011 12:09:43 AM
* =====================================================================================
*/
#include<stdio.h>
#include<pthread.h>
#include<string.h>
pthread_key_t p_key;
void func1()
{
int *tmp = (int*)pthread_getspecific(p_key);//同一线程内的各个函数间共享数据。
printf("%d is runing in %s\n",*tmp,__func__);
}
void *thread_func(void *args)
{
pthread_setspecific(p_key,args);
int *tmp = (int*)pthread_getspecific(p_key);//获得线程的私有空间
printf("%d is runing in %s\n",*tmp,__func__);
*tmp = (*tmp)*100;//修改私有变量的值
func1();
return (void*)0;
}
int main()
{
pthread_t pa, pb;
int a=1;
int b=2;
pthread_key_create(&p_key,NULL);
pthread_create(&pa, NULL,thread_func,&a);
pthread_create(&pb, NULL,thread_func,&b);
pthread_join(pa, NULL);
pthread_join(pb, NULL);
return 0;
}
#gcc -lpthread test.c -o test
# ./test
2 is runing in thread_func
1 is runing in thread_func
100 is runing in func1
200 is runing in func1
#more test.c
/*
* =====================================================================================
* Filename: thead.c
* Description: getspecific
* Created: 05/10/2011 12:09:43 AM
* =====================================================================================
*/
#include<stdio.h>
#include<pthread.h>
#include<string.h>
pthread_key_t p_key;
void func1()
{
int *tmp = (int*)pthread_getspecific(p_key);//同一线程内的各个函数间共享数据。
printf("%d is runing in %s\n",*tmp,__func__);
}
void *thread_func(void *args)
{
pthread_setspecific(p_key,args);
int *tmp = (int*)pthread_getspecific(p_key);//获得线程的私有空间
printf("%d is runing in %s\n",*tmp,__func__);
*tmp = (*tmp)*100;//修改私有变量的值
func1();
return (void*)0;
}
int main()
{
pthread_t pa, pb;
int a=1;
int b=2;
pthread_key_create(&p_key,NULL);
pthread_create(&pa, NULL,thread_func,&a);
pthread_create(&pb, NULL,thread_func,&b);
pthread_join(pa, NULL);
pthread_join(pb, NULL);
return 0;
}
#gcc -lpthread test.c -o test
# ./test
2 is runing in thread_func
1 is runing in thread_func
100 is runing in func1
200 is runing in func1
相关文章推荐
- PHP中的常见魔术方法功能作用及用法实例
- 初学Laravel4常见的问题之四:环境配置
- PHP获取文件夹大小函数用法实例
- Thinkphp模板标签if和eq的区别和比较实例分析
- phpcms v9 数据库操作函数
- 使用 PHPUnit 和 Selenium 进行测试
- ThinkPHP V2.2说明文档没有说明的那些事实例小结
- phpunit+selenium环境搭建
- PHP抓取网页、解析HTML常用的方法总结
- PHP中static关键字以及与self关键字的区别
- PHP中创建图像并绘制文字的例子
- PHP单例模式详细介绍
- PHP+Ajax实时自动检测是否联网的方法
- thinkPHP多表联合查询
- PHP超全局数组(Superglobals)介绍
- PHP中的类型提示(type hinting)功能介绍
- PHP : SOAP 协议调用 Web服务(WebService)(转)
- 7个鲜为人知却非常实用的PHP函数
- 什么是PEAR?什么是PECL?PHP中两个容易混淆的概念解释
- Cloudera Manager5问题之NTP问题