pthread_getspecific和pthread_setspecific使用

pthread_getpecific和pthread_setspecific实现同一个线程中不同函数间共享数据的一种很好的方式

 

/*************************************************************************
    > File Name: pthread.c
    > Author: Arctan
    > Mail: 2757904225@qq.com 
    > Created Time: Wed 28 Aug 2019 05:09:46 PM CST
 ************************************************************************/

#include <stdio.h>
#include <pthread.h>
#include <string.h>

pthread_key_t pkey;

struct Base{
    int a;
    int b;

};

struct Base p1={

    .a=2,
    .b=3.
};

struct Base p2={

    .a=40,
    .b=50,

};

void func1(){

    int* tmp = (int *)pthread_getspecific(pkey);
    printf("func = %s , tmp  = %d\n",__func__,*tmp);
}

void s_func(){

    struct Base* tmp = (struct Base *)pthread_getspecific(pkey);
    printf("func = %s , tmp->a  = %d, tmp->b =%d\n",__func__,(tmp->a),(tmp->b));
}

void* threadFunc(void* args){
    
    pthread_setspecific(pkey,args);

    int* tmp = (int*)pthread_getspecific(pkey);

    *tmp = (*tmp)*100;

    func1();

    return (void *)0;    
}


void* s_threadFunc(void* args){
    
    pthread_setspecific(pkey,args);

    struct Base* tmp = (struct Base*)pthread_getspecific(pkey);

    (tmp->a) = (tmp->a)*100;
    (tmp->b) = (tmp->b)*100;

    s_func();

    return (void *)0;    
}


int main(){

    pthread_t pid_a,pid_b,pid_p1,pid_p2;
    int a = 2;
    int b = 3;

    pthread_key_create(&pkey,NULL);
    pthread_create(&pid_a,NULL,threadFunc,&a);
    pthread_create(&pid_b,NULL,threadFunc,&b);
    
//    a=b=7;

    pthread_create(&pid_p1,NULL,s_threadFunc,&p1);

    pthread_create(&pid_p2,NULL,s_threadFunc,&p2);


    pthread_join(pid_a,NULL);
    pthread_join(pid_b,NULL);

    pthread_join(pid_p1,NULL);
    pthread_join(pid_p2,NULL);
    
    return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值