Thread Specific Data
Thread Specific Data 线程存储
在多线程程序中,所有线程共享程序中的变量。现在有一全局变量,所有线程都可以使用它,改变它的值。而如果每个线程希望能单独拥有它,那么就需要使用线程存储了。表面上看起来这是一个全局变量,所有线程都可以使用它,而它的值在每一个线程中又是单独存储的。这就是线程存储的意义。
下面说一下线程存储的具体用法。
1. 创建一个类型为 pthread_key_t 类型的变量。
2. 调用 pthread_key_create() 来创建该变量。该函数有两个参数,第一个参数就是上面声明的 pthread_key_t 变量,第二个参数是一个清理函数,用来在线程释放该线程存储的时候被调用。该函数指针可以设成 NULL ,这样系统将调用默认的清理函数。
3. 当线程中需要存储特殊值的时候,可以调用 pthread_setspcific() 。该函数有两个参数,第一个为前面声明的 pthread_key_t 变量,第二个为 void* 变量,这样你可以存储任何类型的值。
4. 如果需要取出所存储的值,调用 pthread_getspecific() 。该函数的参数为前面提到的 pthread_key_t 变量,该函数返回 void * 类型的值。
#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); //设置本地存储变量为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

浙公网安备 33010602011771号