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;
}