pthread_getspecific和pthread_setspecific使用
摘自:https://www.cnblogs.com/zhoug2020/p/3951352.html
pthread_getpecific和pthread_setspecific实现同一个线程中不同函数间共享数据的一种很好的方式。
1 /* 2 3 * ===================================================================================== 4 5 * Filename: thead.c 6 7 * Description: getspecific 8 9 * Created: 05/10/2011 12:09:43 AM 10 11 * ===================================================================================== 12 13 */ 14 15 #include<stdio.h> 16 17 #include<pthread.h> 18 19 #include<string.h> 20 21 pthread_key_t p_key; 22 23 24 25 void func1() 26 27 { 28 29 int *tmp = (int*)pthread_getspecific(p_key);//同一线程内的各个函数间共享数据。 30 31 printf("%d is runing in %s\n",*tmp,__func__); 32 33 34 35 } 36 37 void *thread_func(void *args) 38 39 { 40 41 42 43 pthread_setspecific(p_key,args); 44 45 46 47 int *tmp = (int*)pthread_getspecific(p_key);//获得线程的私有空间 48 49 printf("%d is runing in %s\n",*tmp,__func__); 50 51 52 53 *tmp = (*tmp)*100;//修改私有变量的值 54 55 56 57 func1(); 58 59 60 61 return (void*)0; 62 63 } 64 65 int main() 66 67 { 68 69 pthread_t pa, pb; 70 71 int a=1; 72 73 int b=2; 74 75 pthread_key_create(&p_key,NULL); 76 77 pthread_create(&pa, NULL,thread_func,&a); 78 79 pthread_create(&pb, NULL,thread_func,&b); 80 81 pthread_join(pa, NULL); 82 83 pthread_join(pb, NULL); 84 85 return 0; 86 87 } 88 89
#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