博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
pthread_getpecific和pthread_setspecific
阅读量:2224 次
发布时间:2019-05-09

本文共 1133 字,大约阅读时间需要 3 分钟。

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

转载地址:http://fdafb.baihongyu.com/

你可能感兴趣的文章
阿里云《云原生》公开课笔记 第二章 容器基本概念
查看>>
阿里云《云原生》公开课笔记 第三章 kubernetes核心概念
查看>>
阿里云《云原生》公开课笔记 第四章 理解Pod和容器设计模式
查看>>
阿里云《云原生》公开课笔记 第五章 应用编排与管理
查看>>
阿里云《云原生》公开课笔记 第六章 应用编排与管理:Deployment
查看>>
阿里云《云原生》公开课笔记 第七章 应用编排与管理:Job和DaemonSet
查看>>
阿里云《云原生》公开课笔记 第八章 应用配置管理
查看>>
阿里云《云原生》公开课笔记 第九章 应用存储和持久化数据卷:核心知识
查看>>
linux系统 阿里云源
查看>>
国内外helm源记录
查看>>
牛客网题目1:最大数
查看>>
散落人间知识点记录one
查看>>
Leetcode C++ 随手刷 547.朋友圈
查看>>
手抄笔记:深入理解linux内核-1
查看>>
内存堆与栈
查看>>
Leetcode C++《每日一题》20200621 124.二叉树的最大路径和
查看>>
Leetcode C++《每日一题》20200622 面试题 16.18. 模式匹配
查看>>
Leetcode C++《每日一题》20200625 139. 单词拆分
查看>>
Leetcode C++《每日一题》20200626 338. 比特位计数
查看>>
Leetcode C++ 《拓扑排序-1》20200626 207.课程表
查看>>